2014-09-25 47 views
-1

我正在嘗試實現類似於解釋here的內容。編譯器要求接口虛擬構造函數?

我作爲一個接口類中定義:

class IInterface 
{ 
public: 

    virtual bool foo() = 0; 
    virtual void destroy() = 0; 
} 

而且和實現類定義爲:

class MyImplementation : public IInterface 
{ 
    MyImplementation(); 
    ~MyImplementation(); 

    virtual bool foo(); 
    virtual void destroy() {delete this;} 

private: 

    MyImplementation(MyImplementation const&); 
    void operator=(MyImplementation const&); 
} 

extern "C" API MyInterface* __cdecl createMyImplementation(); 

這使用VS2010工作正常發佈模式,但在調試模式下,編譯器爲我這個錯誤:

MyImplementation.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall IInterface::IInterface(void)" ([email protected]@[email protected]) referenced in function "public: __thiscall MyImplementation::MyImplementation(void)" ([email protected]@[email protected]) 

什麼問題,我該如何解決這個問題?

從我的理解,我們不應該有虛擬構造函數...(見this question)。

編輯:

固定排字錯誤。 foo確實有一個正文,這是真正的代碼的簡化版本。

的爲什麼破壞功能的說明:

http://www.parashift.com/c++-faq-lite/delete-this.html

http://eli.thegreenplace.net/2011/09/16/exporting-c-classes-from-a-dll

+5

而不是你'destroy'成員,你應該有一個'虛擬'析構函數。 – 5gon12eder 2014-09-25 19:19:55

+0

鏈接器錯誤(如您正在收到的錯誤)對項目的目標文件/庫/ DLL組織非常敏感。到目前爲止,你沒有提供任何細節。更好地描述它。你的聲明如何在源文件中分佈? – AnT 2014-09-25 19:24:31

+0

所以,雖然每個人都對你的模式很糟糕,但我不認爲它會導致你所看到的錯誤....你如何在MyImplementation中包含IInterface? – IdeaHat 2014-09-25 19:25:59

回答

2
virtual void destroy() {delete this}; 

你在做什麼?硅化? 小心!

在你的情況,MyImplementation::foo()需要有一個機構(即定義),這就是爲什麼你得到了鏈接錯誤

+3

錯誤。 'MyImplementation :: foo()'從未在鏈接器錯誤中提及。 – Gutblender 2014-09-25 19:20:59

+0

+1可能是因爲該函數受到死代碼刪除的影響,該錯誤隱藏在發佈版本中。 – 5gon12eder 2014-09-25 19:21:44

+0

我相信這是正確的答案。我[重現錯誤](http://ideone.com/CCsDKu)使用GCC,並根據[這個線程](http://stackoverflow.com/questions/3065154/undefined-reference-to-vtable),爲'virtual bool foo(){}'定義一個空體來修正錯誤。 – 2014-09-25 20:28:11

1

這似乎是你的問題是,你是不包括在IInterface.obj文件鏈接。在發佈模式下,編譯器意識到ctor是空的並且刪除對它的調用。但它調試模式(單步執行),ctor必須在那裏。我猜你剛剛使用.h文件。