一个基类可以派生出多个派生类,同样,一个派生类可以继承多个基类。
例子:
#include <iostream>
using namespace std;
class BaseA
{
public:
void SetA(int x) { a = x;}//非构造函数
protected:
int a;
};
class BaseB
{
public:
void SetB(int y) { b = y;}//非构造函数
protected:
int b;
};
class Inherit : public BaseA, public BaseB // 定义多继承的派生类
{
public:
int GetAB() { return (a+b); }
};
int main()
{
Inherit Zerone;
Zerone.SetA(12);
Zerone.SetB(5);
cout<<"a+b = "<<Zerone.GetAB()<<endl;
return 0;
}
程序运行显示结果:
多继承下调用派生类的构造函数时,首先要调用该派生类所有基类的构造函数。而处于同一层的基类的构造函数的执行顺序取决于定义派生类时各基类的排列顺序,与定义派生类的构造函数时基类构造函数的排列顺序无关。
从下面这个程序中观察多继承方式下的构造函数的执行顺序。
例子:
#include <iostream>
using namespace std;
class BaseA
{
public:
BaseA(int x)
{
a = x;
cout<<"正在执行BaseA类的构造函数..."<<endl;
}
int GetA() { return a;}
private:
int a;
};
class BaseB
{
public:
BaseB(int y)
{
b = y;
cout<<"正在执行BaseB类的构造函数..."<<endl;
}
int GetB() { return b;}
private:
int b;
};
class Inherit : public BaseA, public BaseB // 定义顺序决定了基类构造函数的调用顺序
{
public:
Inherit(int x, int y, int z):BaseB(z),BaseA(y) //基类构造函数的调用顺序与排列顺序无关
{
c = x;
cout<<"正在执行Inherit类的构造函数..."<<endl;
}
void Show()
{
cout<<"GetA() = "<<GetA()<<endl;
cout<<"GetB() = "<<GetB()<<endl;
cout<<"c = "<<c<<endl;
}
protected:
int c;
};
int main()
{
Inherit Zerone(2013,12,05);
Zerone.Show();
return 0;
}
程序运行显示结果: