多重继承_C++中的多重继承

多重继承是C++的一项功能,其中一个类可以从多个类继承。

继承类的构造函数以它们继承的相同顺序被调用。例如,在以下程序中,在A的构造函数之前调用B的构造函数。

#include using namespace std;   class A { public:   A()  { cout << "A's constructor called" << endl; } };   class B { public:   B()  { cout << "B's constructor called" << endl; } };   class C: public B, public A  // Note the order { public:   C()  { cout << "C's constructor called" << endl; } };   int main() {     C c;     return 0; } 

输出:

B's constructor calledA's constructor calledC's constructor called

析构函数以与构造函数相反的顺序调用。

钻石问题

当一个类的两个超类具有共同的基类时,就会发生钻石问题。例如,在下图中,TA类获取Person类的所有属性的两个副本,这会造成歧义。

e0450bd83cbfe3b7ce9949d8cfc35b07.png

例如,考虑以下程序。

#include using namespace std; class Person {    // Data members of person  public:     Person(int x)  { cout << "Person::Person(int ) called" << endl;   } };   class Faculty : public Person {    // data members of Faculty public:     Faculty(int x):Person(x)   {        cout<
Person::Person(int ) calledFaculty::Faculty(int ) calledPerson::Person(int ) calledStudent::Student(int ) calledTA::TA(int ) called

在上面的程序中,“Person”的构造函数被调用了两次。销毁对象“ta1”时,也会调用“Person”的析构函数两次。因此对象“ta1”具有“Person”所有成员的两个副本,这会造成歧义。解决此问题的方法是使用“virtual”关键字。 我们将“Faculty”和“Student”类设为虚拟基础类,以避免在“ TA”类中使用“Person”的两个副本。例如,考虑以下程序。

#include using namespace std; class Person { public:     Person(int x)  { cout << "Person::Person(int ) called" << endl;   }     Person()     { cout << "Person::Person() called" << endl;   } };   class Faculty : virtual public Person { public:     Faculty(int x):Person(x)   {        cout<

输出:

Person::Person() calledFaculty::Faculty(int ) calledStudent::Student(int ) calledTA::TA(int ) called

在上面的程序中,“Person”的构造函数被调用一次。在上面的输出中要注意的一件事是,默认的“Person”构造函数被调用。当我们使用“virtual”关键字时,即使父类明确调用了参数化构造函数,默认情况下也会调用祖父母类的默认构造函数。

如何调用“ Person”类的参数化构造函数? 构造函数必须在“ TA”类中调用。例如,请参见以下程序。

#include using namespace std; class Person { public:     Person(int x)  { cout << "Person::Person(int ) called" << endl;   }     Person()     { cout << "Person::Person() called" << endl;   } };   class Faculty : virtual public Person { public:     Faculty(int x):Person(x)   {        cout<

输出:

Person::Person(int ) calledFaculty::Faculty(int ) calledStudent::Student(int ) calledTA::TA(int ) called

通常,不允许直接调用祖父母的构造函数,而必须通过父类进行调用。仅在使用“virtual”关键字时才允许使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值