C++多继承时继承了同一个基类的情况

这篇博客探讨了C++中多继承的情景,当多个基类共同继承自同一个基类base0,而派生类myclass又进一步继承这些基类时,如何处理这种重复继承的问题。

base1和base2继承了base0

myclass继承了base1和base2

/*****************************************************/
#ifndef BASE0_H
#define BASE0_H
class base0{
public:
	int x;
	base0(int);
};
#endif


base1和base2都继承 base0
/*****************************************************/
#include "base0.h"
base0::base0(int x)
{
	this->x = x;
}
/*****************************************************/
#ifndef BASE1_H
#define BASE1_H
#include "base0.h"
class base1 :public base0
{
public:
	base1(int);
	//继承
 
};
#endif


/*****************************************************/
#include "base1.h"
base1::base1(int x) :base0(x)
{
	//构造函数
}
/*****************************************************/
#ifndef BASE2_H
#define BASE2_H
#include"base0.h"
class base2 :public base0
{
public:
	base2(int);
	//继承
};
#endif
/*****************************************************/
#include"base2.h"
base2::base2(int x) :base0(x)
{
//构造函数
}


/*****************************************************/
#include "base1.h"
#include "base2.h"
class myclass :public base1, public base2
{
	//同时继承两个类
	//但是他们 有共同基类
public:
	myclass(int);
};
/*****************************************************/
#include "myclass.h"
myclass::myclass(int x) :base1(x), base2(x)
{
   //多继承  
	//构造函数
}
/*****************************************************/
#include 
#include "myclass.h"
using namespace std;
int main(){
	myclass *p = new myclass(12);
	cout << p->base1::x << endl;
	//////////////////////
	//base0 *q = p;  //多继承有两个base0基类  二义性错误
	base0 *q = (base1*)p;
	cout << q->x << endl;
	cin.get();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值