2014-05-15 77 views
0

我在下面的代碼中收到鏈接器錯誤。 如果我將ClientInterface的ClientAPI()函數設置爲純虛擬,則鏈接器錯誤消失。 這種行爲的原因是什麼?實現適配器設計模式時的鏈接器錯誤

// How the interface looks like to the Client 
class ClientInterface 
{ 
public: 
    virtual void ClientAPI(); 
    virtual ~ClientInterface(){} 
}; 

template <class TYPE> //this adaptor class can adapt to any type of legacy application as it is a generic function that uses template parameter to point to any legacy application 
class Adaptor : public ClientInterface 
{ 
public: 
Adaptor(TYPE *objPtr, void (TYPE:: *fnPtr)()) 
{ 
    m_objPtr = objPtr; 
    m_fnPtr = fnPtr; 
} 
void ClientAPI() 
{ 
    /*.... 
    Do the conversion logic reqd to convert the user params into the params expected by your original legacy application... 
    ....*/ 
    (m_objPtr->*m_fnPtr)(); //Would call the method of the legacy application internally 
} 
~Adaptor() 
{ 
    if(m_objPtr) 
     delete m_objPtr;   
} 
private: 
TYPE *m_objPtr; //You can keep either pointer to the Legacy implementation or derive the Legacy implementation privately by your Adaptor class 
void (TYPE:: *m_fnPtr)(); 

}; 

//Adaptee classes below.. 
class LegacyApp1 
{ 
public: 
    void DoThis() 
    { 
     cout<<"Adaptee1 API"<<endl; 
    } 
}; 

//執行類,其中主要定義和我有包括「Adaptor.h」

#include "headers.h" 
#include "Adaptor.h" 

void Adapter() 
{ 
    ClientInterface **interface_ptr = new ClientInterface *[2]; 
    interface_ptr[0] = new Adaptor<LegacyApp1>(new LegacyApp1() , &LegacyApp1::DoThis); 
    interface_ptr[1] = new Adaptor<LegacyApp2>(new LegacyApp2() , &LegacyApp2::DoThat); 
    for(int i = 0; i < 2 ; i++) 
    { 
    interface_ptr[i]->ClientAPI(); 
    } 
} 

int main() 
{ 
    //Testing(); 
    Adapter(); 

    char ch; 
    cin>>ch; 
    return 0; 
} 
+2

您是否可以修改您的問題以包含您所獲得的鏈接器錯誤? – Lilshieste

+0

你的代碼不應該在這一行用分號編譯'virtual〜ClientInterface(){};' – Rakib

+0

@RakibulHasan多餘的分號通常不會造成問題。 (並且,無論好壞,它在Visual Studio中編譯都很好。) – Lilshieste

回答

0

所以在上面的代碼中的校正如下:只要進行以下更改,以第一原代碼的幾行。

// How the interface looks like to the Client 
class ClientInterface 
{ 
public: 
//earlier I forgot to define it, so it was giving linker error as the function is just declared but not defined. 
    virtual void ClientAPI(){} 
    virtual ~ClientInterface(){} 
};   

謝謝。

相關問題