123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- //4.6.2 继承方式
- //继承的语法:class 子类 : 继承方式 父类
- //继承方式一共有三种:
- //?公共继承
- //?保护继承
- //?私有继承
- #include <iostream>
- class Base1
- {
- public:
- int m_A;
- protected:
- int m_B;
- private:
- int m_C;
- };
- class Son1 :public Base1
- {
- public:
- void func()
- {
- m_A = 10; //父类中的公共权限成员到子类中依然是公共权限
- m_A = 10; //父类中的保护权限成员到子类中依然是保护权限
- //m_C = 10; //父类中的私有权限成员到子类中依然是私有权限
- }
- };
- void test01()
- {
- Son1 s1;
- s1.m_A = 100;
- //s1.m_B = 100; //在Son1中 m_B 是保护权限 类外访问不到
- }
- //保护继承
- class Base2
- {
- public:
- int m_A;
- protected:
- int m_B;
- private:
- int m_C;
- };
- class Son2 :protected Base2
- {
- public:
- void func()
- {
- m_A = 100; //父类公共到子类中变成保护权限
- m_B = 100; //父类保护到子类中变成保护权限
- //m_C = 100; //子类访问不到
- }
- };
- void test02()
- {
- Son2 s1;
- //s1.m_A = 1000; //在Son2中 m_A变为保护权限 因此类外访问不到
- //s1.m_B = 1000; //在Son2中 m_A变为保护权限 因此类外访问不到
- }
- class Base3
- {
- public:
- int m_A;
- protected:
- int m_B;
- private:
- int m_C;
- };
- class Son3 :private Base3
- {
- public:
- void func()
- {
- m_A = 100; //父类中公共成员,子类变为私有成员
- m_B = 100; //父类中保护乘员,子类变为私有成员
- //m_C = 100; //父类中私有成员,子类访问不到
- }
- };
- class Grandson :public Son3
- {
- public:
- void func()
- {
- //m_A = 1000; //到了Son3中 m_A变为私有 即使是儿子 也是访问不到
- //m_B = 1000; //到了Son3中 m_B变为私有 即使是儿子 也是访问不到
- }
- };
- void test03()
- {
- Son3 s1;
- //s1.m_A = 1000; //变为私有成员 类外访问不到
- //s1.m_C = 1000; //变为私有成员 类外访问不到
- }
- int main()
- {
- system("pause");
- return 0;
- }
|