我希望下面的代码片段能解释这一切:
struct TBase {
virtual void f() {}
};
struct TDerived : public TBase {
TDerived() {
/* These are all fine either under GCC 4.4.3, ICC 12 and Comeau online: */
f();
this->f();
TBase::f();
this->TBase::f();
/* This one fails under Comeau: */
TBase::TBase();
/* While this one fails in every case: */
//this->TBase::TBase();
/* e.g. GCC says:
test.cpp: In constructor ‘TDerived::TDerived()’:
test.cpp:17: error: invalid use of ‘struct TBase’ */
}
void f() {}
};
问题是:为什么? (即,根据 Comeau C++,为什么 TBase::TBase()
是错误的?为什么 this->TBase::TBase()
甚至更错?)
最佳答案
因为您不能直接调用任何构造函数(§12.1 (2) ISO/IEC 14882:2003(E))。如果要调用基类构造函数,则必须在初始化列表中调用,即:
TDerived() : TBase() {
}
这样做的主要原因是当控制到达派生构造函数的第一个可执行代码行时,可以保证基类对象已经完全构造(§12.6.2 (5) 和 (6) ISO/IEC 14882:2003(E))。由于构造函数通常用于资源获取(即 RAII),如果允许“双重”构造一个对象,将会出错。
关于c++ - 调用基类的构造函数时隐式 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9395228/