C++——类的继承和多态

 一、继承限定词

class X : public Y

public: 父类怎样,子类怎样

protected:父类的public在子类中变成protected

private: 父类的pubic和protected在子类中都变成private

总结:父类中比继承限定词高级的限定词语的等级将会在子类中会降为和继承限定词一样。

         比如,限定词为private时,父类中的public和protected在子类中会降级为private

扫描二维码关注公众号,回复: 2214986 查看本文章

二、无参构造函数和析构函数的调用顺序:

1、子类构建对象时,先调用父类的构造函数,再调用子类的构造函数

2、子类的对象销毁时,先调用子类的析构函数,再调用父类的析构函数

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class GrandFarther
 6 {
 7 public:
 8     GrandFarther()
 9     {
10         cout << "GrandFarther();" << endl;
11     }
12     ~GrandFarther()
13     {
14         cout << "~GrandFarther();" << endl;
15     }
16 };
17 class Father : public GrandFarther
18 {
19 public:
20     Father()
21     {
22         cout << "Father();" << endl;
23     }
24     ~Father()
25     {
26         cout << "~Father();" << endl;
27     }
28 };
29 class Son : public Father
30 {
31 public:
32     Son()
33     {
34         cout << "Son();" << endl;
35     }
36     ~Son()
37     {
38         cout << "~Son();" << endl;
39     }
40 };
41 
42 int main()
43 {
44     Son xiaoming;
45     return 0;
46 }

输出为:

GrandFarther();

Farther();

Son();

~Son();

~Farther(); 

~GrandFarther();

猜你喜欢

转载自www.cnblogs.com/FengZeng666/p/9327482.html