多继承概念:
一个类有多个直接基类的继承关系成为多继承
多继承声明语法:
class 派生类名:访问控制 基类名0,访问控制 基类名1.......
{
数据成员和成员函数声明
}
多继承的派生类构造和访问
多个基类的派生类构造函数可以用初始时调用基类构造函数初始化数据成员
执行顺序与单继承构造函数情况类似,多个直接基类构造函数执行顺序取决于定义派生类时指定的各个继承基类的顺序
一个派生类对象拥有多个直接或间接基类的成员,不同名成员访问不会出现二义性。如果不同的基类有同名成员,派生类对象访问时应该加以识别
#include<iostream>
using namespace std;
class base1
{
public:
base1(int b1)
{
this->b1 = b1;
cout << "我是b1的构造函数"<< endl;
}
~base1()
{
cout << "我是b1的析构函数"<< endl;
}
private:
int b1;
};
class base2
{
public:
base2(int b2)
{
this->b2= b2;
cout << "我是b2的构造函数" << endl;
}
~base2()
{
cout << "我是b2的析构函数" << endl;
}
private:
int b2;
};
class B :public base1,public base2//先执行b1的构造函数,b2的构造函数,B的构造函数
{
public:
B(int b2, int b1, int c) :base2(b2),base1(b1)
{
this->c = c;
cout <<"我是B的构造函数" << endl;
}
~B()
{
cout <<"我是B的析构函数" << endl;
}
private:
int c;
};
void objectplay()
{
B b1(1, 2, 3);
}
void main()
{
objectplay();
system("pause");
}