我有一些静态常量字符串作为我的 C++ 类的私有成员。我知道 .h 中的声明和 .cpp 实践中的定义(和初始化)。在类构造函数中,我调用一个使用这些静态字符串的函数。令人惊讶的是,在构造函数中,字符串保持未初始化(空字符串),这会产生问题。
有人可以指出这里可能出了什么问题吗?我一直使用静态常量字符串,但从未遇到过这种情况。
更新:m_data 在 utility() 中保持为空。我有一个 Test 类对象作为另一个类的私有成员。
这是我正在使用的一种代码:
// Test.h
class Test
{
public:
Test();
private:
void utility();
static const std::string m_data;
};
// Test.cpp
const std::string Test::m_data = "Data";
Test::Test()
{
utility();
}
void Test::utility()
{
//use m_data here
}
你的 TEST 类型的对象是全局的吗?
如果是这样,那么您就会遇到初始化顺序的问题。
ie.
int main()
{
std::cout << "Main Entered" << std::endl;
Test t; // This should work
}
Test plop; // This may not work depending
解决方案是使用静态方法来获取字符串:
class Test
{
static std::string const& getData()
{
static std::string const data("PLOP");
return data;
}
// STUFF
// Remove this line
// static const std::string m_data;
Test::Test()
{
std::cout << "Test::Test()" << std::endl;
Utility();
}
};
// If "Test::Test()" is printed before "Main Entered"
// You have a potential problem with your code.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)