实现适配器设计模式时链接器错误
Linker error while implementing Adapter design pattern
我在下面的代码中得到链接器错误。如果我将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的执行类,并且包含了" adapter .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;
}
因此上述代码中的更正如下:只需对原始代码的前几行进行以下更改。
// 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(){}
};
谢谢。
相关文章:
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- CMake 错误:链接器命令失败,退出代码为 1 和 cpp.o 文件
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 如何修复 clang: 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- Android NDK.Build命令失败.未定义的引用.clang++:错误:链接器命令失败,退出代码为1
- 使用cmake错误链接boost日志
- 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用):在 Macbook 上
- C++ XCODE ld:找不到体系结构x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -
- clang:错误:链接器命令失败,C++代码中的退出代码为 1(使用 -v 查看调用)
- 静态库中的 g++ 错误链接函数
- 未定义的参考错误链接天然函数Android
- C++编译错误:ld:找不到体系结构x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v
- QT Q_PROPERTY错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- ld:找不到体系结构x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- OSX MOJAVE -LD:架构X86_64 clang找不到符号:错误:链接器命令失败,出口代码1
- C 错误链接器命令失败了出口代码1(使用-V查看调用)
- LD:架构x86_64 clang找不到符号:错误:链接器命令失败,出口代码1(使用-v to See
- 聚输出错误 - 链接列表
- Xcode链接器错误:链接器命令失败,退出代码为1(使用-v查看调用)
- 尝试构建C DLIB示例无法与数百个未定义的参考错误链接