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를 참조합니까? 여기에 모호성이 있습니다.

솔루션 1 : 도메인 구성원 운영자를 사용하면 단점으로 인해 데이터 중복이 발생합니다.

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

해결 방법 2 : 가상 상속 사용

#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