继承—多重基类和虚拟基类

多重基类即之前的多重继承,在利用多重继承生成派生类时,会出现一些问题。

class test1
{
	int x;
public:
	int getx(){...}
	...
};
class test2:public test1
{
};
class test3:public test1
{
};
class test4:public test2,public test3
{
};
test4 x;
int a,b;
a=x.test2::getx();//正确
b=x.test3::getx();//正确
a=x.getx();//错误

为了解决这个问题,我们引入虚拟基类

class test1
{
	...
};
class test2:virtual test1
{
};
class test3:virtual test1
{
};
class test4:public test2,public test3
{
};

在基类名前加上virtual关键字,表示该基类为虚拟基类。以这种方式生成的派生类test4中,只包含一个test1的对象。

1、非虚拟基类

/*说明非虚拟基类的用法和作用*/
#include<iostream>
using namespace std;
class test1
{
	int x;
public:
	test1():x(10)
	{
	}
	int get()
	{
		return x;
	}
	void set(int s)
	{
		x=s;
	}
};
class test2:public test1
{
};
class test3:public test1
{
};
class test4:public test3,public test2
{
};
int main()
{
	test4 p;
	p.test2::set(11);
	p.test3::set(12);
	cout<<"test2:"<<p.test2::get()<<endl;
	cout<<"test3:"<<p.test3::get()<<endl;
}

在这里插入图片描述
2、虚拟基类

/*说明虚拟基类的用法合作同*/
#include<iostream>
using namespace std;
class test1
{
	int x;
public:
	test1():x(10)
	{
	}
	int get()
	{
		return x;
	}
	void set(int s)
	{
		x=s;
	}
};
class test2:virtual public test1
{
};
class test3:virtual public test1
{
};
class test4:public test3,public test2
{
};
int main()
{
	test4 p;
	p.test2::set(11);
	p.test3::set(12);
	p.set(13);
	cout<<"test2:"<<p.test2::get()<<endl;
	cout<<"test3:"<<p.test3::get()<<endl;
	cout<<"p.get():"<<p.get()<<endl;
} 

在这里插入图片描述
3、尽管test2test3都是虚拟基类,但是他们的基类是独立存在的。

/*说明虚拟基类的基类是独立存在的*/
#include<iostream>
using namespace std;
class test1
{
	int x;int y;
public:
	test1():x(0),y(0)
	{
	}
	test1(int a,int b):x(a),y(b)
	{
	}
	void setx(int a)
	{
		x=a;
	}
	void sety(int b)
	{
		y=b;
	}
	void disp()
	{
		cout<<"x="<<x<<" "<<"y="<<y<<endl;
	}
};
class test2:virtual public test1
{
};
class test3:virtual public test1
{
};
class test4:public test2,public test3
{
};
int main()
{
	test4 p;
	p.setx(10);p.sety(10);
	cout<<"test4:";p.disp();
	test2 q=p;
	q.setx(20);
	test3 r=p;
	r.sety(20);
	cout<<"test2:";q.disp();
	cout<<"test3:";r.disp();
}

在这里插入图片描述
由上述程序和运行结果我们可以看出,虽然test2test3都是test4的虚拟基类,但是test2test3的基类是独立存在的,当我改变其中一个内容时,另一个并不随之改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值