多继承的访问注意点

#include <iostream>
using namespace std;
class Base { 
public:
 virtual ~Base(){ cout << "Base destruction" << endl;}
 virtual ostream&print(){ cout << "Base print" << endl;  return cout;}
 virtual void log(){cout << "Base log" << endl;}
 virtual void debug(){ cout << "Base debug" << endl; }
 virtual void readOn(){ cout << " Base readOn" << endl;}
 virtual void writeOn(){ cout << "Base writeOn" << endl;}
 // ...
};
class Derived1 : virtual  public Base { 
public:
 virtual ~Derived1(){ cout << "Derived1 destruction" << endl;}
 virtual void writeOn(){ cout << "Derived1 writeOn" << endl; }
 virtual void cuddle(){cout << "Derived1 cuddle" << endl;}
 // ...
};
class Derived2 : virtual public Base { 
public:
 virtual ~Derived2(){ cout << "Derived2 destruction" << endl; }
 virtual void readOn(){ cout << "Derived2 readOn" << endl;}
 // ...
};
class MI : public Derived1, public Derived2 { 
public:
 virtual ~MI(){ cout << "MI destruction " << endl;}
 virtual ostream&print(){ cout << "MI print" << endl; return cout;}
 virtual void debug(){cout << "MI debug" <<endl; }
 virtual void cuddle(){cout << "MI cuddle" << endl;}
 // ...
};
//============================================================
//当派生类从基类A,B类派生出来时.A从基类AFather派生出来.
//当用派生类C对象的地址初始化或赋值给基类A或基类AFather指针或引用时,
//C接口中"C特有的部分"以及"B类部分"就都不能被访问.
//============================================================
void main()
{
 Base *pb = new MI; //当Derived1 和Derived2 不是以虚拟方式继承Base,将会发生ambiguous
 //pb->cuddle(); 不能访问MI中特有的成员函数
  pb->print();
  pb->readOn();
  pb->log();
  pb->debug();
  pb->writeOn();
  delete pb;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值