曲径通幽论坛

标题: 多重继承 [打印本页]

作者: beyes    时间: 2011-8-26 20:16
标题: 多重继承
派生类可以从两个或者多个基类中继承,如下程序,类 derived 从类 base1 和类 base2 中继承:
[C++] 纯文本查看 复制代码

#include <iostream>
using namespace std;

class base1 {
    protected:
        int x;

    public:
        void showx() { cout << x << endl; }
};

class base2 {
    protected:
        int y;
    public:
        void showy() { cout << y << endl; }
};

//从多个类中继承
class derived: public base1, public base2 {
    public:
        void set (int i, int j) { x = i; y = j; }
};

int main()
{
    derived ob;

    ob.set(10, 20);    //派生类中定义的函数
    ob.showx();    //从 base1 中继承
    ob.showy();    //从 base2 中继承

    return 0;
}

运行输出:
$ ./mulinherit
10
20
要从多个基类中继承,必须使用逗号将基类分隔开来,并且要为每个基类指定访问控制符,这里 base1 和 base2 的访问控制符都为 public 。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2