【发布时间】:2012-09-03 07:05:17
【问题描述】:
我有两个链接错误,我不知道代码有什么问题以及如何修复它们:
main.obj:-1: error: LNK2019: unresolved external symbol "public: __thiscall A::A(void)" (??0?$A@VB@@@@QAE@XZ) 在函数 "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) 在函数“public: void __thiscall B::run(void)" (?run@B@@QAEXXZ)
稍微解释一下代码:
这个类必须执行派生类的函数。函数 exec 从派生类中调用,并带有派生类参数中的函数。这个函数的签名是void function();
//header.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
//header.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 类派生一个类,并将派生类作为模板参数传递。然后我通过run()函数执行函数exec。
//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;
}
谁能告诉我这是怎么回事?...
【问题讨论】:
标签: c++ class templates linker external