继承
1 语法
2 继承方式
继承方式一共有三种:
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
| class Base{ public: int A; private: int B; protected: int C; }; class Son1:public Base{ public: void func(){ A = 10; C = 30; } }; class Son2:protected Base{ public: void func(){ A = 10; C = 30; } }; class Son3:private Base{ public: void func(){ A = 10; C = 30; } }; void test01(){ Son1 s1; s1.func(); s1.A = 100;
Son2 s2; s2.func();
Son3 s3; s3.func();
}
|
3 继承中的对象模型
父类中私有成员也被子类继承下去了,只是由编译器隐藏后访问不到。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Base{ public: int A; private: int B; protected: int C; }; class Son1:public Base{ public: int D; }; void test01(){ Son1 s1; cout<<"sizeof Son1 = "<<sizeof(Son1)<<endl; }
|
4 继承中的构造和析构顺序
子类继承父类后,当创建子类对象,也会调用父类的构造函数。先构造父类,析构一般和构造顺序相反。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Base{ public: Base(){ cout<<"Base的构造函数"<<endl; } ~Base(){ cout<<"Base的析构函数"<<endl; } }; class Son:public Base{ public: Son(){ cout<<"Son的构造函数"<<endl; } ~Son(){ cout<<"Son的析构函数"<<endl; } }; void test01(){ Base b; cout<<endl; Son s1; }
|
运行结果:
1 2 3 4 5 6
| Base的构造函数 Base的构造函数 Son的构造函数 Son的析构函数 Base的析构函数 Base的析构函数
|
5 继承中同名处理方式
子类与父类出现同名的成员:
- 访问子类同名成员 直接访问即可
- 访问父类同名成员 需要加作用域
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
| class Base{ public: int A; Base(){ A = 100; } void func(){ cout << "Base - func()调用" << endl; } void func(int a){ cout << "Base - func(int a)调用" << endl; } }; class Son:public Base{ public: int A; Son(){ A = 200; } void func(){ cout << "Son - func()调用" << endl; } }; void test01(){ Son s; cout << "Son下的m_A = " << s.A << endl; cout << "Base下的m_A = " << s.Base::A << endl; s.func(); s.Base::func(); s.Base::func(10); }
|
6 继承中同名静态成员处理方式
静态成员和非静态成员出现同名,处理方式一致
- 访问子类同名成员 直接访问即可
- 访问父类同名成员 需要加作用域
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Base{ public: static int A; static void func(){ cout<<"Base的静态成员函数"<<endl; } }; int Base::A = 100; class Son:public Base{ public: static int A; }; int Son::A = 200; void test01(){ Son s; cout << "Son下的m_A = " << s.A << endl; cout << "Base下的m_A = " << s.Base::A << endl; cout << "Son下的m_A = " << Son::A << endl; cout << "Base下的m_A = " << Son::Base::A << endl; Son::Base::func(); }
|
7 多继承语法
C++允许一个类继承多个类,多继承可能会引发父类中有同名成员出现,需要加作用域区分
语法: class 子类 :继承方式 父类1 , 继承方式 父类2...
示例:
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
| class Base1 { public: Base1(){ m_A = 100; } public: int m_A; };
class Base2 { public: Base2(){ m_A = 200; } public: int m_A; };
class Son : public Base2, public Base1 { public: Son(){ m_C = 300; m_D = 400; } public: int m_C; int m_D; };
void test01() { Son s; cout << "sizeof Son = " << sizeof(s) << endl; cout << s.Base1::m_A << endl; cout << s.Base2::m_A << endl; } int main() { test01(); return 0; }
|