c++ - 从基类构造函数调用纯虚函数

我有一个包含纯虚函数的基类 MyBase:

void PrintStartMessage() = 0

我希望每个派生类在它们的构造函数中调用它

然后我把它放在基类(MyBase) 构造函数中

 class MyBase
 {
 public:

      virtual void PrintStartMessage() =0;
      MyBase()
      {
           PrintStartMessage();
      }

 };

 class Derived:public MyBase
 {     

 public:
      void  PrintStartMessage(){

      }
 };

void main()
 {
      Derived derived;
 }

但我收到链接器错误。

 this is error message : 

 1>------ Build started: Project: s1, Configuration: Debug Win32 ------
 1>Compiling...
 1>s1.cpp
 1>Linking...
 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)

我想强制所有派生类...

A- implement it

B- call it in their constructor 

我必须怎么做?

最佳答案

有很多文章解释了为什么你不应该在 C++ 的构造函数和析构函数中调用虚函数。看看here和 here详细了解此类通话期间幕后发生的情况。

简而言之,对象是从基础构造到派生的。因此,当您尝试从基类构造函数调用虚函数时,尚未发生从派生类的覆盖,因为尚未调用派生构造函数。

https://stackoverflow.com/questions/8630160/

相关文章:

c++ - 库已链接,但引用未定义

c++ - 与 win32 CRITICAL_SECTION 相比的 std::mutex 性能

c++ - 如何使用 C++ 模板减少编译时间

c++ - 什么是 C++ 内联类?

c++ - C++ 标准是否对 float 的表示做了任何规定?

c++ - 编译lua代码,存储字节码然后加载并执行

c++ - "&s[0]"是否指向 std::string 中的连续字符?

c++ - 三元表达式中的逗号混淆

c++ - 如何在 Windows 上找到 Qt5 CMake 模块

c++ - 析构函数可以是最终的吗?