c++ - 调用基类的构造函数时隐式 'this'

标签 c++ this

我希望下面的代码片段能解释这一切:

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/

相关文章:

c++ - 为什么优化会杀死这个功能?

类的 C++ 函数重载

c++ - 使用模板的类型转换有奇怪的行为

c++ - 在纯 DOS 模式下写入文件?

java - 在构造函数结束之前如何引用/处理 "this"?

C++:Dungeon Crawler - 更新数组时出现问题

C++ this(在这种情况下,什么是指向当前类的链接)

javascript - "this"未按预期工作

javascript - 尝试找出如何使用 "this"寻址各个菜单项

javascript - javascript 中的递归函数、setTimeout 和 'this' 关键字