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

#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

猜你喜欢

转载自blog.csdn.net/paulliam/article/details/80434532