虚拟继承和层次结构中的构造函数调用的问题

时间:2019-04-26 11:55:43

标签: c++ c++14 virtual-inheritance

我有一个简单的继承结构,例如: Base <-- Child1 <-- Child2
以及以下主要方法:

int main(int argc, char* argv[]) {
    Child2 c2(111, 222);
    cout << endl;
    cout << "c2 - baseValue: " << c2.getBaseValue() << endl;
    cout << "c2 - child1Value: " << c2.getChild1Value() << endl;
    return 0;
}

我将Eclipse CDT与MacOSX Mojave一起使用。

注意:我在Eclipse的C / C ++构建设置中添加了-std=gnu++14选项,以避免出现delegating constructors are permitted only in C++11错误。

当我运行可执行文件时,将导致以下输出:

Base int Ctor
 |- _baseValue: -1
Base Default Ctor
Child1 int,int Ctor
 |- _baseValue: 111
 |- _child1Value: 222
Child2 int,int Ctor
 |- _baseValue: 111
 |- _child1Value: 222

c2 - baseValue: -1
c2 - child1Value: 222

我的问题是:
1.为什么baseValue的值为-1而child1Value的期望值为?
2.为什么将调用Base的默认构造函数?没有子默认构造函数也不会被调用。

// Base.h
class Base {
public:
    Base();
    Base(int _num);
    virtual ~Base();
    int getBaseValue() const;
private:
    int baseValue;
};
// Base.cpp
Base::Base() : Base(-1) {
    cout << "Base Default Ctor" << endl;
}

Base::Base(int _baseValue) : baseValue(_baseValue) {
    cout << "Base int Ctor" << endl;
    cout << " |- _baseValue: " << _baseValue << endl;
}

Base::~Base() {
}

int Base::getBaseValue() const {
    return baseValue;
}
// Child1.h
class Child1: virtual public Base {
public:
    Child1();
    Child1(int _baseValue);
    Child1(int _baseValue, int _child1Value);
    virtual ~Child1();
    int getChild1Value() const;
private:
    int child1Value;
};
// Child1.cpp
Child1::Child1() : Child1(-1, -1) {
    cout << "Child1 Default Ctor" << endl;
}

Child1::Child1(int _baseValue) : Child1(_baseValue, -1) {
    cout << "Child1 int Ctor" << endl;
    cout << " |- _baseValue: " << _baseValue << endl;
}

Child1::Child1(int _baseValue, int _child1Value) : Base(_baseValue), child1Value(_child1Value) {
    cout << "Child1 int,int Ctor" << endl;
    cout << " |- _baseValue: " << _baseValue << endl;
    cout << " |- _child1Value: " << _child1Value << endl;
}

Child1::~Child1() {
}

int Child1::getChild1Value() const {
    return child1Value;
}
// Child2.h
class Child2: virtual public Child1 {
public:
    Child2();
    Child2(int _baseValue);
    Child2(int _baseValue, int _child1Value);
    virtual ~Child2();
};
// Child2.cpp
Child2::Child2() : Child2(-1, -1) {
    cout << "Child2 Default Ctor" << endl;
}

Child2::Child2(int _baseValue) : Child2(_baseValue, -1) {
    cout << "Child2 int Ctor" << endl;
    cout << " |- _baseValue: " << _baseValue << endl;
}

Child2::Child2(int _baseValue, int _child1Value) :  Child1(_baseValue, _child1Value) {
    cout << "Child2 int,int Ctor" << endl;
    cout << " |- _baseValue: " << _baseValue << endl;
    cout << " |- _child1Value: " << _child1Value << endl;
}

Child2::~Child2() {
}

0 个答案:

没有答案