初始化静态类成员

时间:2013-07-15 03:57:41

标签: c++ class static initializer

我正在尝试初始化静态类成员并且没有运气。这是一个测试:

文件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()将做一些真正的工作来设置静态成员。有人可以指出错误吗?

2 个答案:

答案 0 :(得分:1)

正如错误消息所示,static std::string *sp;必须在某处定义,因为它与class Test的任何实例都没有关联。

将其添加到全局范围的Test.cpp将解决问题:

std::string *Test::sp = NULL;

答案 1 :(得分:1)

这是C ++的一个令人尴尬的“功能”:你需要做一些手握,以确保链接器可以生成符号。您需要选择某些 cpp文件,并确保在任何其他符号中不会出现相同的符号(否则链接器在遇到重复符号时将失败)。所以你必须在cpp文件中为你的类做另一个静态成员变量声明,如下所示:

std::string * Test::sp; // or sp = NULL;