C++ 多态性 2-- 3使用多重继承 4模拟抽象类

80 篇文章 0 订阅
#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
     16-03-04 3使用多重继承 4模拟抽象类-是一个虚拟的抽象类,它的虚函数仍然具有功能
	 那就是啥事也不做;真正的抽象类具有一个或者一个以上的真正没有任何功能的虚函数
---------------------------------*/
class human	//模拟抽象类 这个虚函数仅仅是为了让它的子类继承并具体化功能
{
public:
	virtual void smart(){}
	virtual void beautiful(){}
	human(){cout<<"构造human"<<endl;}
	virtual ~human(){cout<<"析构human"<<endl;}
};
class father:virtual public human	//加virtual修饰符,防止son到human存在模棱两可的转换
{
public:
	void smart(){cout<<"父亲很聪明"<<endl;}
//	virtual void beautiful(){cout<<"父亲也很beautiful"<<endl;}
	father(){cout<<"构造father"<<endl;}
	virtual ~father(){cout<<"析构father"<<endl;} //基类得用virtual修饰,才能正常完成析构
};
class mother:virtual public human	//加virtual修饰符,防止son到human存在模棱两可的转换
{
public:
	virtual void beautiful(){cout<<"母亲很漂亮。"<<endl;}
	mother(){cout<<"构造mother"<<endl;}
	virtual ~mother(){cout<<"析构mother"<<endl;} //基类得用virtual修饰,子类对象才能正常完成析构
};
class son:public father,public mother	//多重继承
{
public:
	 void beautiful(){cout<<"儿子也很帅"<<endl;}
	 void smart(){cout<<"儿子也很聪明"<<endl;}
	son(){cout<<"构造son"<<endl;}
	~son(){cout<<"析构son"<<endl;}
};
int main()
{
//	father *pf;
//	mother *pm;
	human *ph;
	int choice=0;
	bool quit;
	while(1)
	{
		quit=false;
		cout<<"0)退出 1)父亲 2)儿子 3)母亲: ";
		cin>>choice;
		switch(choice)
		{
			case 0:
				quit=true;
				break;
			case 1:
				ph =new father;
				ph->beautiful(); //父亲的beautiful被注释掉了,故调用human类的beautiful
				delete ph;
				break;
			case 2:
				ph =new son; //由于son由father和mother派生而来,而father和mother又是由human派生的
				ph->beautiful(); //所以,son这时候就有了两义性,即son到human存在模棱两可的转换
				ph->smart();
				delete ph;
				break;
			case 3:
				ph =new mother;
				ph->beautiful();
				delete ph;
				break;
			default:
				cout<<"请输入0到2之间的数字:";
				break;
		}
		if(quit)
			break;	
	}


	cout<<"程序结束"<<endl;
	return 0;
}

运行结果:

0)退出 1)父亲 2)儿子 3)母亲: 1
构造human
构造father
析构father
析构human
0)退出 1)父亲 2)儿子 3)母亲: 2
构造human
构造father
构造mother
构造son
儿子也很帅
儿子也很聪明
析构son
析构mother
析构father
析构human
0)退出 1)父亲 2)儿子 3)母亲: 3
构造human
构造mother
母亲很漂亮。
析构mother
析构human
0)退出 1)父亲 2)儿子 3)母亲: 0
程序结束
Press any key to continue

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值