2

下面是多重继承中面临的一个菱形问题,

class Base {
 public:
  Base() {
    cout << "Empty Base constructor " << endl; 
  }
  Base(const string & strVar) { 
    m_strVar = strVar; 
    cout << m_strVar << endl;
  }
  virtual ~Base() {
    cout << "Empty Base destructor " << endl;
  }
  virtual const string & strVar() const { 
   return m_strVar; 
  }

  string m_strVar;
};

class Derived1: public virtual Base {
 public:
  Derived1() {
    cout << "Empty Derived1 constructor " << endl; 
  }
  Derived1(const string & strVar) : Base(strVar) {
    cout << " Derived1 one arg constructor" << endl;
  }
  ~Derived1() {
    cout << "Empty Derived1 destructor " << endl;
  }
};

class Derived2: public virtual Base {
 public:
  Derived2() {
    cout << "Empty Derived2 constructor " << endl; 
  }
  Derived2(const string & strVar) : Base(strVar) {
    cout << "Derived2 one arg constructor" << endl;
  }
  ~Derived2() {
    cout << "Empty Derived2 destructor " << endl;
  }
};

class Derived: public Derived1, public Derived2 {
 public:
  Derived(const string & strVar) : Derived1(strVar), Derived2(strVar) {
    cout << "Derived Constructor " << endl; 
  }
  ~Derived() {
    cout << "Empty Derived destructor " << endl;
  }
};

int main() {
  Derived derObj ("Print this if you can ! "); 
}

我得到的输出是

  1. 空基构造函数
  2. Derived2 一个 arg 构造函数
  3. Derived1 一个 arg 构造函数
  4. 派生构造函数
  5. 空派生析构函数
  6. 空 Derived2 析构函数
  7. 空 Derived1 析构函数
  8. 空基析构函数

我想知道为什么我的 derObj 参数(即“如果可以打印”)没有打印出来,输出也不像

  1. 空基构造函数
  2. Derived2 一个 arg 构造函数
  3. 如果可以的话,打印这个!
  4. Derived1 一个 arg 构造函数
  5. 派生构造函数
  6. 空派生析构函数
  7. 空 Derived2 析构函数
  8. 空 Derived1 析构函数
  9. 空基析构函数
4

1 回答 1

6

这与虚拟继承有关。

当一个类被虚拟继承时,层次结构中最派生的类有责任调用它的构造函数:here Derived

由于Base是默认可构造的并且您没有精确任何内容,Derived因此调用Base.

如果要打印字符串,请使用:

Derived(const string & strVar) : Base(strVar), Derived1(strVar), Derived2(strVar)
{
  std::cout << "Derived Constructor\n"; 
}

您可以删除默认构造函数以让编译器诊断问题,但并非所有编译器都会提供非常有用的消息。

于 2012-02-16T09:29:51.957 回答