Possible Duplicate:
C++ template, linking error
我有两个链接错误,我不知道代码出了什么问题以及如何修复它们:
main.obj:-1: error: LNK2019: unresolved external symbol "public: __thiscall A::A(void)" (??0?$A@VB@@@@QAE@XZ) referenced in function "public: __thiscall B::B(void)" (??0B@@QAE@XZ)
和
main.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall A::exec(void (__thiscall B::*)(void))" (?exec@?$A@VB@@@@QAEXP8B@@AEXXZ@Z) referenced in function "public: void __thiscall B::run(void)" (?run@B@@QAEXXZ)
稍微解释一下代码:
该类必须执行派生类中的函数。函数 exec 从派生类调用,并使用派生类参数中的函数。该函数的签名是void function();
//标题.h
#ifndef HEADER_H
#define HEADER_H
template <class T>
class A
{
public:
typedef void (T::*ExtFunc)();
A();
void funcA();
void exec(ExtFunc func);
};
#endif // HEADER_H
//标题.cpp
#include "header.h"
template<typename T>
A<T>::A() { }
template<typename T>
void A<T>::funcA()
{
cout << "testA\n";
}
template<typename T>
void A<T>::exec(ExtFunc func)
{
(T().*func)();
}
在 main.cpp
我从 A 类派生一个类,并将派生类作为模板参数传递。然后我执行函数 exec
通过run()
功能。
//main.cpp
#include <iostream>
#include "header.h"
using namespace std;
class B : public A<B>
{
public:
B() { }
void run()
{
exec(&B::funcB);
}
void funcB()
{
cout << "testB\n";
}
};
int main()
{
B ob;
ob.run();
return 0;
}
谁能告诉我这是怎么回事吗?...
最佳答案
当您使用模板时,通常您不能将实现放在 .cpp 文件中 - 您必须将整个类放在 header 中。因此将所有代码从 header.cpp 移至 .h。
您可以通过在 .cpp 文件内进行显式实例化来解决此问题 - 实例化特定类型的模板。但这要求您提前知道哪些类型需要实例化,并且会阻止您添加新的实例化。唯一的好处是减少编译时间。
关于c++ - C++ 中的 LNK2019 链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12243339/