一 概述
本节课介绍多重继承,一个子类有两个及两个以上父类的情况。并结合实例进行分析
二 分析
- 子类son,有两个父类:father、mother
- 左侧是父类,右侧是子类对象
三 示例演示及结果输出
3.1 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include<iostream> using namespace std;
class father{
public: void smart(){cout<<"父亲很聪明"<<endl;} //virtual void beautiful(){} father(){cout<<"构造father"<<endl;} virtual ~father(){cout<<"析构father"<<endl;} }; class mother {
public: virtual void beautiful(){cout<<"母亲很漂亮。。"<<endl;} mother(){cout<<"构造mother"<<endl;} virtual ~mother(){cout<<"析构mother"<<endl;} }; class son:public father,public mother {
public: virtual void beautiful(){cout<<"儿子也很帅"<<endl;} son(){cout<<"构造son"<<endl;} ~son(){cout<<"析构son"<<endl;}
}; int main() { father *pf; mother *pm; int choice=0; while(choice<99) { bool quit=false; cout<<"(0)退出(1)父亲(2)儿子:"; cin>>choice; switch(choice) { case 0:quit=true; break; case 1:pf=new father; break; case 2:pm=new son; pm->beautiful(); //pm->smart(); delete pm; break; default:cout<<"请输入从0到2之间的数字。"; } if(quit) { break; } } cout<<"程序结束"<<endl; return 0; }
|
3.2 输出结果
1 2 3 4 5 6
| (0)退出(1)父亲(2)儿子:2 儿子也很帅 父亲很聪明 析构son 析构father (0)退出(1)父亲(2)儿子:
|