class Base1 {public:int m_a;};class Base2 {public:int m_a;};class Son :public Base1,public Base2 {public:int m_b;};
该实例中,Son类继承了两个base,且都有同名成员变量ma;
D:\C++\LearnCpp>cl /d1 reportSingleClassLayoutSon LearnCpp.cpp用于 x86 的 Microsoft (R) C/C++ 优化编译器 19.27.29112 版版权所有(C) Microsoft Corporation。保留所有权利。LearnCpp.cppclass Son size(12):+---0 | +--- (base class Base1)0 | | m_a| +---4 | +--- (base class Base2)4 | | m_a| +---8 | m_b+---Microsoft (R) Incremental Linker Version 14.27.29112.0Copyright (C) Microsoft Corporation. All rights reserved./out:LearnCpp.exeLearnCpp.obj
多继承语法
C++允许一个类继承多个类
语法:class 子类 :继承方式 父类1 , 继承方式 父类2...
多继承可能会引发父类中有同名成员出现,需要加作用域区分
C++实际开发中不建议用多继承
示例:
class Base1 {public:Base1(){m_A = 100;}public:int m_A;};class Base2 {public:Base2(){m_A = 200; //开始是m_B 不会出问题,但是改为mA就会出现不明确}public:int m_A;};//语法:class 子类:继承方式 父类1 ,继承方式 父类2class 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();system("pause");return 0;}
总结: 多继承中如果父类中出现了同名情况,子类使用时候要加作用域
