正在初始化静态类成员
Initializing a static class member
我正在尝试初始化一个静态类成员,但没有成功。这里有一个测试:
文件测试.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;
相关文章:
- 使用静态成员声明类时遇到问题
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 从相同类型的静态成员进行类内初始化
- 是否通过单元化指针UB访问静态类成员
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 从静态成员函数访问私有非静态类变量 - C++
- 在子类中填充静态类成员
- 作为成员的静态类模板实例会导致未解析的外部符号错误
- uninit_member:非静态类成员字段 m_cJobState.bstatus 未在此构造函数中初始化,也不在其调
- uninit_member:非静态类成员m_wszParams未在此构造函数中初始化,也不在它C++中调用的任何函数中初
- 说明通过指针访问非静态类成员函数
- 静态类数据成员的线程安全
- 具有静态成员的类的前向声明
- 枚举不是非静态数据成员或类的基类
- 静态类成员的使用
- 静态类成员不是与 this 指针没有关联吗?
- 使用静态类成员而不是私有字段之间的速度差异是什么?
- 如何在 Visual Studio 中显示模板的静态类成员
- 即使没有析构函数,非静态类成员也会被销毁吗?
- 静态模板函数访问静态类成员