I'm developing a class that receive as parameter a template class object. Since it has a template object, I'm defining all methods in the .h file (no .cpp).
I have static const variables that I declare in .h file and I initialize them in the .cpp file (this is the only purpose of the .cpp file in my case). I access these static const variables in some methods.
I can compile this class without problems. The problem appears when I try to include the header file in the file that will execute it, then I have the following error:
UnitTest.obj : Error LNK2001: unresolved external symbol "public: static char const * const A::FNUMBER
I have tried to define methods in the .cpp file, but then when I try to compile I have linker errors in all methods of the mentioned template class.
Here an example of code:
#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
#include "A.h"
const float A::FNUMBER = 1.3f;
#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.
}
As I say, If I do not use the static const variables inside the class, there are no errors. What I'm doing wrong? Thanks.
Are you sure that you are compiling/linking with A.cpp/Ao? Your code should compile with g++ UnitTest.cpp A.cpp
assuming TemplateClass.h doesn't have an external .cpp file.
包括包含static const
变量初始化的.cpp
文件,即可解决此问题。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.