C++ 多态性 3-- 5纯虚函数与抽象类

80 篇文章 0 订阅
#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
     16-05 5纯虚函数与抽象类
	 纯虚函数是彻底无任何功能的,不能直接调用它,它只有被子类继承并赋予新功能后才能被调用。
	 真正的抽象类具有一个或者一个以上的真正没有任何功能的虚函数
---------------------------------*/
class human	//模拟抽象类 这个虚函数仅仅是为了让它的子类继承并具体化功能
{
public:
	virtual void smart()=0;		//初始化为0,就变成了纯虚函数
	virtual void beautiful()=0;	//初始化为0,就变成了纯虚函数
	human(){cout<<"构造human"<<endl;}
	virtual ~human(){cout<<"析构human"<<endl;}
};
class father:virtual public human	//加virtual修饰符,防止son到human存在模棱两可的转换
{
public:
	virtual void smart(){cout<<"父亲很聪明"<<endl;}
	virtual void beautiful(){cout<<"父亲很帅"<<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;}
	virtual void smart(){cout<<"母亲不聪明"<<endl;}//mother类具化smart()
	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()
{
	human *ph;
//	ph =new human;	//不能实例化抽象类,抽象类创造出来的对象也是抽象的,是没有使用意义的
//	ph->smart();	//故编译报错 'human' : cannot instantiate abstract class due to following members:


	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
				ph->smart();
				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:  //由于mother类没有具化smart(),所以只能调用基类human的smart,而其又不允许调用
				ph =new mother; //故编译报错:'mother' : cannot instantiate abstract class due to following members
				ph->beautiful();
				ph->smart();
				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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值