在基类构造函数中调用虚函数 [英] Calling virtual function in a Base Class Constructor

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

问题描述

大家好,我在理解以下行为方面遇到问题.也许有人可以向我解释一下?
我有一个像这样的基类:

Hello everyone i''m having problems to understand the following behaviour. Maybe someone can explain this to me?
I have a base class like:

class BaseClass
{
    private:
        int _A;
        virtual void Initialize() = 0;
    public:
        BaseClass()
        {
           _A = 1;
           Initialize();
        }
}



还有一个派生类



And a derived class

class Child : public BaseClass
{
      public:
         Child() : BaseClass() {};
         void Initialize()
         {
              //do specific initialization here
         }
}



所以我期望的是,在实例化Child类时,将调用基类构造函数,该构造函数使用派生类实现的Initialize方法.
我得到的是关于Initialize方法的链接器错误.
但是,当在普通函数中使用Initialize方法时,它会按预期工作.



So what i''m expecting is, that when instantiating the Child class, the base class constructor gets called which uses the Initialize method implemented by the derived class.
What im getting is a linker error about the Initialize method.
But when using the Initialize method in an ordinary function it works as expected.

推荐答案

例如,参见Scott Meyers'' [ ^ ].
See, for instance, Scott Meyers'' "Never Call Virtual Functions during Construction or Destruction"[^].


那是正常行为.
*构造函数:
因为未初始化派生类,所以无法调用任何虚函数.成员的状态未定义.
*析构函数:
无法调用任何虚函数,因为派生类已被初始化.成员状态在最终操作中是未定义的或无效的.也就是说,您不得将任何值设置为已定义的值(即NULL).
问候.

[edit]
其他(我忘了)
假设您有这样的课程:
Thats the normal behaviour.
* Constructor:
cannot call any virtual function because the derived class is not initialized. The state of the memebers is undefined.
* Destructor:
cannot call any virtual function because the derived class is already deinitialized. The member state is undefined or invalid from the final operations. Thats you must not set any values to a defined value (i.e. NULL).
Regards.

[edit]
additional (i forgot)
imagine you have classes like this:
class A{};
class B : public A{}
class C : public B{}



"C类"的功能将按以下方式调用:



the functions for "class C" will be called as follows:

this->A::A();
this->B::B();
this->C::C();
// other code
this->C::~C();
this->B::~B();
this->A::~A();


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

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