初始化静态成员 TestClassObject 显示错误 LNK2001:未解析的外部符号。
class TestClass
{
public:
string sClassName;
string sName;
string sDescription;
};
class TestA
{
private:
static void InitInfo();
static TestClass TestClassObject;
};
void TestA::InitInfo()
{
TestClassObject.sName = "Name";
TestClassObject.sClassName = "ClassName";
TestClassObject.sDescription = "Description of class";
}
最佳答案
您必须在类定义之外定义静态数据成员。在类定义中它只是被声明而没有被定义。
例如
#include <iostream>
#include <string>
using namespace std;
class TestClass
{
public:
string sClassName;
string sName;
string sDescription;
};
class TestA
{
private:
static TestClass InitInfo();
static TestClass TestClassObject;
};
TestClass TestA::InitInfo()
{
return { "Name", "ClassName", "Description of class" };
}
TestClass TestA::TestClassObject = InitInfo();
int main()
{
}
关于c++ - 如何从静态类函数初始化静态类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58932973/