簡體   English   中英

派生模板 class 不調用構造函數

[英]Derived of template class not calling constructor

我正在使用 C++ 實現事件模板,如下所示

模板.h

template<typename EventArg>
class Event {
public:
    typedef void (*EventHandle)(const EventArg&);
    vector<EventHandle> EventHandles;


protected:
    virtual void Init() { throw EventNotInitialized();};
    Event() 
    {
        printf("Event() \n");
        Init();
    }
};

事件.h

struct E_EventArgs {
    string data;
};
class E_Event : public Event<E_EventArgs>
{
public:
    static E_Event * Get() {
        static auto ins = new E_Event();
        return ins;
    }
protected:
    void Init() override {
        printf("E_Event() Init() \n");
    }
    E_Event() {
        Init();
        printf("E_Event() \n");
    }
};

然后我調用E_Event::Get()來訪問E_Event 但這是日志:

Event()

我使用 arm-oe-linux-gnueabi-g++ (gcc 版本 6.4.0 (GCC))

為什么不調用E_Event的構造函數?

您觀察到的並不是從構造函數調用虛擬 function 的結果。

在構造函數中,虛擬調用機制被禁用,因為派生類的覆蓋尚未發生。 對象是從基向上構造的,“先基后派生”。

這意味着當您從E_Event的構造函數調用Init()時, Init() () 的最新“最新”覆蓋版本是基礎 class Event

但是,在您的情況下,不會發生來自E_Event的構造函數的Init()調用。

構造派生 class 時,也會構造基 class 的實例。 考慮這個簡單的例子。

#include <iostream>
class Base
{
public:
    Base()
    {
        std::cout<<"Base constructor"<<std::endl;
    }
};
class Derived: public Base
{
public:
    Derived()
    {
        std::cout<<"Derived constructor";
    }
};
int main()
{
  Derived();
}

output 將是

Base constructor
Derived constructor

可以看到, Base的構造函數也被調用了。 因此,從E_Event的構造函數中,也調用了Event() ,它已經拋出異常,這就是為什么E_Event中的任何內容都不會被調用的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM