1. 程式人生 > >C++ 虛繼承 筆記

C++ 虛繼承 筆記

#include <iostream>
#include <iomanip>
using namespace std;
class X
{
protected:
	int a;
public:
	X() { a = 1; cout << setw(3) << "X:" << a << endl; }
	void fund() { cout << "X標記" << endl; }
};
class X1 : virtual public X
{
public:
	X1() { a += 1; cout << setw(3) << "X1:" << a << endl; }
	void fund() { cout << "X1標記" << endl; }
};
class X2 : virtual public X
{
public:
	X2() { a += 2; cout << setw(3) << "X2:" << a << endl; }
	void fund() { cout << "X2標記" << endl; }
};
class Y :public X1, public X2
{
public:
	Y() { cout << setw(3) << "Y:" << a << endl; }
	void fun() { cout << "Y標記" << endl; }
};
int main()
{
	Y obj;
	obj.fun();
	//obj.fund(); 訪問不明確不通過編譯
	obj.X2::fund();
	obj.X1::fund();
	obj.X::fund();
	return 0;
}

 

輸出結果:
 X:1
X1:2
X2:4
 Y:4
Y標記
X2標記
X1標記
X標記