实现适配器设计模式时链接器错误

时间:2014-05-15 05:47:45

标签: c++ design-patterns adapter

我在下面的代码中遇到链接器错误。 如果我将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;
    }
};

//执行类,其中定义了main,并且我包含了“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; 
}

1 个答案:

答案 0 :(得分: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(){}
};        

感谢。