虚继承和虚基类

虚继承主要解决在多重继承中的菱形继承问题,也就是说 B和C类同时继承了A类,然后D类继承了B,C类,那么D类的虚表就会有重复的函数指针。

#include<iostream>
using namespace std;

//虚基类
class Person
{
	public:
		Person(){cout<<"Person()"<<endl;}
		~Person(){cout<<"~Person()"<<endl;}

		Person(string name)
		//	:name(name) //3.3 error
		{
			cout<<"Person(string)"<<endl;
		}

		void talk()
		{
			cout<<"i'm person"<<endl;
		}

	protected:
		string name;
};

class Mother:virtual public Person//虚继承
{
	public:
		Mother(){cout<<"Mother()"<<endl;}
		~Mother(){cout<<"~Mother()"<<endl;}

		Mother(string name)
		//	:Person(name) //3.2
		{
			cout<<"Mother(string)"<<endl;
		}

		void talk()
		{
			cout<<"i'm mother"<<endl;
		}

		void cook()
		{
			cout<<"cooking"<<endl;
		}
};

class Father:virtual public Person//虚继承
{
	public:
		Father(){cout<<"Father()"<<endl;}
		~Father(){cout<<"~Father()"<<endl;}

		Father(string name)
		//	:Person(name) //3.2
		{
			cout<<"Father(string)"<<endl;
		}

		void talk()
		{
			cout<<"i'm Father"<<endl;
		}

		void repair()
		{
			cout<<"repairing"<<endl;
		}
};

class Child:public Father, public Mother
{
	public:
		Child(){cout<<"Child"<<endl;}
		~Child(){cout<<"~child"<<endl;}

		Child(string name)
			//:name(name) //2.error

			//:Father(name), Mother(name) //3.1
			//Person(name); //4.ok
		{
			this->name=name;//1.ok
			cout<<"Child(string)"<<endl;
		}

		void talk()
		{
			cout<<"i'm child"<<endl;
			cout<<"my name is name "<<name<<endl;
		}

};

main()
{
	Child child("jack");

	child.cook();
	child.repair();

	child.talk();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值