为什么只有基类默认构造函数在虚拟基础多重继承中被调用? [英] Why only base class default constructor is called in virtual base multiple inheritance?

查看:178
本文介绍了为什么只有基类默认构造函数在虚拟基础多重继承中被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多继承中,我有一个虚拟 Base 类,它由类 A 和类 B A B AB 的基类。请参阅下面的代码。
A B 的构造函数中, Base(string)构造函数。我希望得到以下输出:

In multiple inheritance, I have a virtual Base class which is inherited by class A and class B. A and B are base classes of AB. Please see the code below. In constructor of A and B, Base(string) constructor is called. I am expecting to get following output:

Base::Base(std::string)

A::A()

B::B()

我得到以下输出:

Base::Base()

A::A()

B::B()

为什么默认构造函数 Base 正在呼叫?

Why default constructor of Base is being called?

#include<iostream>
#include<string>
using namespace std;

class Base{
public:
        Base(){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
        Base(string n):name(n){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
private:
string name;
};

class A : public virtual Base {
public:
        A():Base("A"){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
private:
string name;
};

class B : public virtual  Base {
public:
        B():Base("B"){
                cout<<__PRETTY_FUNCTION__<<endl;
        }
private:
string name;
};

class AB : public A, public B{

};

int main(){
        AB a;
}


推荐答案

对象。因此 AB 的构造函数调用 Base 构造函数,但由于您未指定 AB ,它的默认构造函数只是调用 Base 的默认构造函数。

The virtual base is constructed by the most-derived object. So AB's constructor call the Base constructor, but since you didn't specify a constructor for AB, its default constructor just calls the default constructor of Base.

您可以从 AB 调用字符串构造函数:

You could call the string-constructor from AB like this:

struct AB : A, B
{
    AB() : Base("hello"), A(), B() { }
};

请注意,构造函数 A :: A() B:B()不会调用 Base

Note that the constructors A::A() and B:B() do not call the Base constructor in this setup!

这篇关于为什么只有基类默认构造函数在虚拟基础多重继承中被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆