C++多继承(virtual public)时,顶级对象只有一个的验证

#include <iostream>
using namespace std;
class A
{
public:
	A():x(1){}
	virtual void to_str(){
		cout<<"A.x:"<<x<<" @ "<<hex<<this<<dec<<endl;
	}
	virtual void set_x(int xx){
		cout<<"A setx called"<<endl;
		x = xx;
	}
private:
	int x;
};

class B1: /* virtual */ public A
{
public:
	B1():x(21){}
	virtual void to_str(){
		cout<<"B1 to_str begin"<<endl;
		A::to_str();
		cout<<"B1.x:"<<x<<endl;
		cout<<"B1 to_str end"<<endl;
	}
	virtual void set_b1x(int xx){
		cout<<"B1 setx called"<<endl;
		x = xx;
	}
	void set_B1_A_x(int xx){
	    set_x( xx );
	}
private:
	int x;
};

class B2: /* virtual */ public A
{
public:
	B2():x(22){}
	virtual void to_str(){
		cout<<"B2 to_str begin"<<endl;
		A::to_str();
		cout<<"B2.x:"<<x<<endl;
		cout<<"B2 to_str end"<<endl;
	}
	virtual void set_b2x(int xx){
		cout<<"B2 setx called"<<endl;
		x = xx;
	}
private:
	int x;
};

class C: public B1, public B2
{
public:
    C():x(3){}
	virtual void to_str(){
		B1::to_str();
		B2::to_str();
		cout<<"C.x:"<<x<<endl;
	}
	virtual void set_cx(int xx){
		cout<<"C setx called"<<endl;
		x = xx;
	}
private:
	int x;
};

int main()
{
	C c;
	c.to_str();
	cout<<"########################"<<endl;
    //  A(B1(c)).setx(110);
	//	((A)(B1)c).setx(220);
	/*
	A *pc = &(B1)c;    //error: talking address of temporary
	pc->setx(330);
	*/
	//	c.set_x(440);   //error: ambiguous
	
	c.set_B1_A_x(550);  //success !

	cout<<"########################"<<endl;
	c.to_str();

    return 0;
}

  

 

 

posted @ 2012-12-13 14:33  庚武  Views(280)  Comments(0)    收藏  举报