正在初始化静态类成员

Initializing a static class member

本文关键字:成员 静态类 初始化      更新时间:2023-10-16

我正在尝试初始化一个静态类成员,但没有成功。这里有一个测试:

文件测试.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;

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

在全局范围内将其添加到Test.cpp将修复问题:

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