C++多继承带来的二义性问题的解决方案

多继承(菱形或称钻石继承)编程可以带来很多便利,也更贴近生活但也带来很多麻烦

#include<iostream>
using namespace std;

class B1
{
    
    
public:
	void output();
};

class B2
{
    
    
public:
	void output();
};
void B1::output()
{
    
    
	cout << "call the class B1" << endl;
}
void B2::output()
{
    
    
	cout << "call the class B2" << endl;
}

class A :public B1, public B2
{
    
    
public:
	void show();
};
void A::show()
{
    
    
	cout << "call the class A" << endl;
}


int main()
{
    
    
	A a;
	a.output();
	a.show();
}

在这里插入图片描述

程序报错,a.output()这函数指的是B1的还是B2的?这里有二义性。

解决方案一:使用域成员运算符,缺点会带来数据冗余

int main()
{
    
    
	A a;
	a.B1::output();
	a.show();
}

解决方案二:用虚继承

#include<iostream>
using namespace std;

class B1
{
    
    
public:
	virtual void output() = 0;
	virtual int add(int a, int b) = 0;
};

class B2
{
    
    
public:
	virtual void output()=0;
	virtual int mult(int a, int b) = 0;
};


class A :public B1, public B2
{
    
    
public:
	virtual int add(int a, int b)
	{
    
    
		cout << "A: add() readly" << endl;
		return a + b;
	}
	virtual int mult(int a, int b)
	{
    
    
		cout << "A: mult() readly" << endl;
		return a * b;
	}
	virtual void output()
	{
    
    
		cout << "A output" << endl;

	}
};


int main()
{
    
    
	A a;
	int x, y;
	x = a.add(10, 20);
	y = a.mult(10, 20);
	cout << "x = " << x << "\ty = " << y << endl;
	a.output();

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_50188452/article/details/114363339