我正在尝试初始化一个静态类成员,但没有成功。这是一个测试:
文件Test.h
#include <string>
class Test {
public:
static void init(char*);
private:
static std::string *sp;
};
文件Test.cpp
#include "Test.h"
// Initialize the class
void
Test::init(char *foo) {
Test::sp = new std::string(foo);
}
int main(int argc, char** argv) {
Test::init(argv[1]); // call the class initializer
}
链接器失败并显示:
Undefined symbols for architecture x86_64:
"Test::sp", referenced from:
Test::init(char*) in Test-OK13Ld.o
ld: symbol(s) not found for architecture x86_64
在现实世界中,init() 将做一些实际工作来设置静态成员。有人能指出错误吗?
最佳答案
这是 C++ 的一个令人尴尬的“功能”:您需要进行一些操作以确保链接器可以生成符号。您需要选择一些 cpp
文件,并确保在任何其他文件中相同符号不会发生此类处理(否则链接器在遇到重复符号时将失败)。因此,您必须在 cpp
文件中为您的类再次声明静态成员变量,如下所示:
std::string * Test::sp; // or sp = NULL;
关于c++ - 初始化静态类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646550/