从基类构造函数调用纯虚函数 [英] call to pure virtual function from base class constructor

查看:50
本文介绍了从基类构造函数调用纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a base class MyBase that contains a pure virtual function:

void PrintStartMessage() = 0

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

I want each derived class to call it in their constructor

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

then I put it in base class(MyBase) constructor

 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:UsersShmuelianDocumentsVisual Studio 2008Projectss1Debugs1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)

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

I want force to all derived classes to...

A- implement it

B- call it in their constructor 

我必须怎么做?

推荐答案

有很多文章解释了为什么在 C++ 中永远不要在构造函数和析构函数中调用虚函数.看看这里此处 详细了解此类调用期间幕后发生的情况.

There are many articles that explain why you should never call virtual functions in constructor and destructor in C++. Take a look here and here for details what happens behind the scene during such calls.

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

In short, objects are constructed from the base up to the derived. So when you try to call a virtual function from the base class constructor, overriding from derived classes hasn't yet happened because the derived constructors haven't been called yet.

这篇关于从基类构造函数调用纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆