【发布时间】:2013-07-12 20:43:33
【问题描述】:
我正在尝试初始化一个静态类成员并且没有运气。这是一个测试:
文件测试.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() 会做一些实际的工作来设置静态成员。有人能指出错误吗?
【问题讨论】:
-
static std::string *sp;未定义。 -
还有,为什么要使用指向 std::string 的指针?
-
好吧,我知道未定义的 ref / unresolved extern 是什么,因此该链接相当广泛。 @itwasntpete 的评论提醒我,我所拥有的只是一份声明。所以显然我需要在类定义中(但在之外)定义。
标签: c++ class static initializer