多继承的“二义性”问题

版权声明:个人爱好,可随便转载 https://blog.csdn.net/qq_43528087/article/details/88994369

一般来说,在派生类中对基类成员的访问应该是唯一的,但是,由于在多继承情况下,可能出现对基类中某个成员的访问不唯一性情况,这称为对基类成员访问的多继承二义性问题

分两种情况:
first: 派生类的多个基类中调用其同名成员时可能出现二义性
second:派生类有共同基类时访问公共基类成员可能出现二义性

例子:

#include <iostream>
using namespace std;

class A
{
	public:
	A() {cout << "A constructor called" << endl;}
};
class B1 : public A
{
	public:
	B1(){cout << "B1 constructor called" << endl;}
};
class B2 : public A
{
	public:
	B2(){cout << "B2 constructor called" << endl;}
};
class C : public B1, public B2
{
	public:
	C(){cout << "C constructor called" << endl;}
};

int main(int argc,char **argv)
{
	C cc;
	system("pause");
	return 0;
}

在这里插入图片描述
在实例化C时,调用了两次基类的构造函数;虚基类的引入解决了此类问题
修改后的代码如下:

#include <iostream>
using namespace std;

class A
{
	public:
	A() {cout << "A constructor called" << endl;}
};
class B1 : virtual public A
{
	public:
	B1(){cout << "B1 constructor called" << endl;}
};
class B2 : virtual public A
{
	public:
	B2(){cout << "B2 constructor called" << endl;}
};
class C : public B1, public B2
{
	public:
	C(){cout << "C constructor called" << endl;}
};

int main(int argc,char **argv)
{
	C cc;
	system("pause");
	return 0;
}

在这里插入图片描述
有调试结果可得,只调用了一次基类A的构造函数

猜你喜欢

转载自blog.csdn.net/qq_43528087/article/details/88994369