【发布时间】:2015-09-07 02:43:23
【问题描述】:
我正在开发一个接收模板类对象作为参数的类。由于它有一个模板对象,我在 .h 文件中定义所有方法(没有 .cpp)。
我在 .h 文件中声明了静态 const 变量,并在 .cpp 文件中对其进行了初始化(在我的情况下,这是 .cpp 文件的唯一用途)。我在某些方法中访问这些静态 const 变量。
我可以毫无问题地编译这个类。当我尝试在将执行它的文件中包含头文件时出现问题,然后出现以下错误:
UnitTest.obj : Error LNK2001: unresolved external symbol "public: static char const * const A::FNUMBER
我尝试在 .cpp 文件中定义方法,但是当我尝试编译时,在提到的模板类的所有方法中都出现了链接器错误。
这里是代码示例:
头文件(.h)
#ifndef A_H
#define A_H
#include "TemplateClass.h"
typedef TemplateClass<int, char> A_TemplateClass;
class A{
public:
static const float FNUMBER;
//Due to I refer a template class, I have to implement all my methods in .h file,
//else I have a lot of linker errors (1 for each template class method)
A(A_TemplateClass &atc) : aTemplateClass(atc) {};
void method1(){
//Use the static const variable
//If I do not access this variable, there is no problems.
float f = FNUMBER + 3.2;
[...]
}
void method2(){
//Use the static const variable
//If I do not access this variable, there is no problems.
float f = FNUMBER + 3.3;
[...]
}
private:
A_TemplateClass aTemplateClass;
};
#endif
.cpp 文件
#include "A.h"
const float A::FNUMBER = 1.3f;
UnitTest.cpp 文件
#include "TemplateClass.h"
#include "A.h"
int main(){
TemplateClass<int, char> x;
A a(x);
float f = A::FNUMBER; //Linker ERROR
//If I delete the above line, there are no errors.
}
正如我所说,如果我不在类中使用静态 const 变量,则不会出现错误。 我做错了什么?谢谢。
【问题讨论】:
-
您的
UnitTest.cpp是否链接到包含A::FNUMBER定义的.cpp文件?您可能没有将单元测试与实现文件链接起来。 -
将
;代替.放在typedef的末尾,并用;终止类A- 这编译完美。 -
A_TemplateClass、method1、method2等内容真的与手头的问题相关吗?或者您可以删除它们以创建更好的Minimal, Complete, and Verifiable example?因为按原样,这看起来不是最小的或可验证的(鉴于 Arnon Zilca 刚刚指出的语法错误)。 -
SIntax 错误已修复。实际上,在我的真实课堂上,我有 ;在课程结束时和一个;代替 。在 typedef 的末尾。如果我尝试访问静态 const 变量,method1 和 method2 仅与显示链接器错误有关。
-
请注意,在我的情况下,类编译,只有当我尝试从 UnitTest.cpp 包含它时才会出现错误