c++ - 初始化静态类成员

标签 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() 将做一些实际工作来设置静态成员。有人能指出错误吗?

最佳答案

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

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

关于c++ - 初始化静态类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646550/

相关文章:

c++ - 警告 C4267 : 'initializing' : conversion from 'size_t' to 'UINT'

javascript - 如何在 HTML 文件中重复使用 base64 图像

javascript - 可以在magento block 中使用js吗?

class - 在 Dart 中,从变量调用静态方法时出现问题

java - 为什么说在class dog中的构造函数dog无法应用于给定类型?它似乎可以运行,但是会引发错误,那是为什么?

c++ - 构造函数中的错误 : no instance of overloaded function, (C++)

c# - 使用具有属性的静态方法

c++ - 如何检查对象中是否存在信号?

c++ - 空终止字符串 : Use '\0' or just 0?

c++ - 在类构造函数中调用命名 lambda 与调用实际私有(private)函数的优点