c++多继承语法
c++允许一个类继承多个类
语法:
class 子类: 继承方式 父类1,继承方式 父类2
多继承可能引发父类中的同名成员出现,要加作用域区分。C++开发中不建议用多继承。
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 class Father1 6 { 7 public: 8 int m_A; 9 int m_B; 10 Father1() 11 { 12 m_A = 100; 13 m_B = 200; 14 } 15 16 }; 17 class Father2 18 { 19 public: 20 int m_A; 21 Father2() 22 { 23 m_A = 300; 24 } 25 }; 26 27 class son1 :public Father1, public Father2//类的多继承:class 子类:继承方式 父类,继承方式 父类2.。。 28 { 29 public: 30 int m_A; 31 son1() 32 { 33 m_A = 100; 34 } 35 }; 36 37 38 void test1() 39 { 40 son1 p1; 41 cout << "p1.m_A=" << p1.m_A << endl; 42 cout << "p1.Father1::m_A=" << p1.Father1::m_A << endl;//不同父类中的同名成员要加作用域 43 cout << "p1.Father2::m_A=" << p1.Father2::m_A << endl; 44 } 45 int main() 46 { 47 test1(); 48 return 0; 49 }

浙公网安备 33010602011771号