C++_多重继承(多个父类或基类)

C++_多重继承(多个父类或基类)

1、简单实现多重继承
注意:沙发床继承沙发和床

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Sofa {
public:
	void watchTV(void) { cout<<"watch TV"<<endl; }
};

class Bed {
public:
	void sleep(void) { cout<<"sleep"<<endl; }
};

class Sofabed : public Sofa, public Bed {
};

int main(int argc, char **argv)
{
	Sofabed s;
	s.watchTV();
	s.sleep();
	return 0;
}

2、多重继承造成的二义性的问题
注意:沙发也有重量的床也有重量,当派生类沙发床想要,设置重量时候不知道改调用哪一个

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Sofa {
private:
	int weight;
public:
	void watchTV(void) { cout<<"watch TV"<<endl; }
	void setWeight(int weight) { this->weight = weight; }
	int getWeight(void) const { return weight; }
};

class Bed {
private:
	int weight;
public:
	void sleep(void) { cout<<"sleep"<<endl; }
	void setWeight(int weight) { this->weight = weight; }
	int getWeight(void) const { return weight; }
};

class Sofabed : public Sofa, public Bed {
};

int main(int argc, char **argv)
{
	Sofabed s;
	s.watchTV();
	s.sleep();

	//s.setWeight(100); /* error, 有二义性 */
	s.Sofa::setWeight(100);
	
	return 0;
}

3、解决二义性的问题(引入虚拟继承)
注意:虚拟继承架构
在这里插入图片描述
虚拟继承的内存情况
在这里插入图片描述

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Furniture {
private:
	int weight;
public:
	void setWeight(int weight) { this->weight = weight; }
	int getWeight(void) const { return weight; }
};

class Sofa : virtual public Furniture {
private:
	int a;
public:
	void watchTV(void) { cout<<"watch TV"<<endl; }
};

class Bed : virtual public Furniture {
private:
	int b;
public:
	void sleep(void) { cout<<"sleep"<<endl; }
};

class Sofabed : public Sofa, public Bed {
private:
	int c;
};

int main(int argc, char **argv)
{
	Sofabed s;
	s.watchTV();
	s.sleep();

	s.setWeight(100);
	
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值