Fork me on GitHub

多重继承

单一继承:一个父类,可以有多个子类

多重继承:多个父类,只有一个子类

程序示例    //多重继承

 1 #include <iostream>
 2 using namespace std;
 3 class father//父类一
 4 {
 5 public:
 6     void set_father(int a){ tall = a; }
 7     void print_father(){ cout << "tall=" << tall << endl; }
 8 private:
 9     int tall;
10 };
11 class mother//父类二
12 {
13 public:
14     void set_mother(int a){ weight = a; }
15     void print_mother(){ cout << "weight=" << weight << endl; }
16 private:
17     int weight;
18 };
19 class son :public father, public mother//冒号后面是访问权限,
20                                         //不同父类的访问权限可以不同,父类之间用逗号隔开
21 {
22 public:
23     void set_son(int a){ age = a; }
24     void print_son(){ print_father(); print_mother(); cout << "age=" << age << endl; }
25 private:
26     int age;
27 };
28 int main()
29 {
30     son a;
31     father b;
32 
33     a.set_father(185);//直接调用并设置
34     a.set_mother(55);
35     a.set_son(20);
36     a.print_son();
37     //后面是测试
38     b.print_father();//结果:产生随机数,因为没有初始化
39 
40     b.set_father(100);//赋初值,tall=100
41     b.print_father();
42 
43     a.print_son();//发现设置父类并不影响子类的数据成员
44     return 0;
45 }

结果显示

 

posted @ 2015-08-07 09:21  夏成都  阅读(167)  评论(0编辑  收藏  举报