c ++-为什么需要调用嵌套继承的抽象构造函数?

时间:2018-08-07 00:36:01

标签: c++ inheritance constructor abstract

主题可能令人困惑,所以这是代码示例(沙盒here):

class AbstractA {
 protected:
  int wibble_;
 public:
  AbstractA(int wibble) : wibble_(wibble) { }
  virtual ~AbstractA() { }
  virtual void DoThing(void) = 0;  // Pure virtual method.
};

class AbstractB : public virtual AbstractA {
 public:
  AbstractB(int wibble) : AbstractA(wibble) { }
  virtual ~AbstractB() { }
  virtual void DoOtherThing(void) = 0;  // Pure virtual method.
};

class DerivedA : public AbstractA {
 public:
  DerivedA(int wibble) : AbstractA(wibble) { }
  virtual ~DerivedA() { }
  virtual void DoThing(void) { wibble_ = 1; }  // Implement pure virtual method.
};

class DerivedB : public AbstractB {
 public:
  //DerivedB(int wibble) : AbstractB(wibble) { }  // Error -- see below.
  DerivedB(int wibble) : AbstractA(wibble), AbstractB(wibble) { }  // Works.
  virtual ~DerivedB() { }
  virtual void DoThing(void) { wibble_ = 2; }  // Implement AbstractA method.
  virtual void DoOtherThing(void) { wibble_ = 3; }  // Implement AbstractB method.
};

我有两个抽象类,AbstractAAbstractBAbstractB使用AbstractA关键字从virtual继承,因此DoThing()仍然是纯虚拟的。 AbstractB构造函数调用AbstractA的构造函数,该构造函数初始化wibble_数据成员。

然后我有两个派生类DerivedADerivedBDerivedA继承AbstractA,从其构造函数调用AbstractA(int),并实现AbstractA::DoThing()。同样,DerivedB继承并实现AbstractB

这是我不了解的部分。 DerivedB不直接继承AbstractA。但是编译器坚持认为AbstractA的构造函数中对DerivedB的构造函数的调用是隐式的。如果我尝试使用第一个DerivedB构造函数(在示例中注释掉),则会出现此错误:

foo.h: In constructor 'DerivedB::DerivedB(int)':
foo.h:31:42: error: no matching function for call to 'AbstractA::AbstractA()'

那么DerivedB为什么需要调用其基类(AbstractA)继承的类(AbstractB)的构造函数?我的意思是,AbstractB(int)在其初始值设定项中调用AbstractA(int),因此调用AbstractA(wibble), AbstractB(wibble)不会有效地调用AbstractA(wibble)两次-直接一次,一次是从AbstractB()的一次构造函数?

0 个答案:

没有答案