主题可能令人困惑,所以这是代码示例(沙盒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.
};
我有两个抽象类,AbstractA
和AbstractB
。 AbstractB
使用AbstractA
关键字从virtual
继承,因此DoThing()
仍然是纯虚拟的。 AbstractB
构造函数调用AbstractA
的构造函数,该构造函数初始化wibble_
数据成员。
然后我有两个派生类DerivedA
和DerivedB
。 DerivedA
继承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()
的一次构造函数?