初始化静态成员变量值的正确位置

Proper place to initialize the value of static member variable

本文关键字:位置 静态成员 变量值 初始化      更新时间:2023-10-16

构造函数类中初始化我的静态成员变量是否正确?

// CFoo.h
class CFoo
{
public:
    CFoo();
    ~CFoo();
    static std::string str;
};
// CFoo.cpp
CFoo::CFoo()
{
    str = "HELLO";
}
CFoo::~CFoo()
{
}

谢谢

您还没有define静态成员。您需要在 CFoo.cpp 中定义它。

呜.cpp

std::string CFoo::str;  // define str
CFoo::CFoo()
{
    str = "HELLO";  // reset str is fine
}
CFoo::~CFoo()
{
}