【发布时间】:2019-07-24 23:51:34
【问题描述】:
我正在使用static 变量。参考Unresolved external symbol on static class members后,修改程序为Abc::ct
#include <iostream>
class Abc
{
private:
static unsigned int ct;
public:
void f1()
{
for (int i = 0; i < 5; ++i)
f2();
}
void f2() {
Abc::ct = 0;
if (Abc::ct == 0)
std::cout << "Zero iteration\n";
std::cout << Abc::ct << "\t";
++Abc::ct;
}
};
int main()
{
Abc obj;
obj.f1();
}
但在 MSVC 中出现 error LNK2001: unresolved external symbol "private: static unsigned int Abc::ct" 或在 g++ 中出现 undefined reference to Abc::ct 错误。如何在Abc 类中定义静态变量?
【问题讨论】:
-
Abc::ct必须在你的类之外定义,在main之上。 -
有什么方法可以只在类中定义
static变量? (当然没有const) -
从您的示例中,实例数据似乎比静态数据更合适
-
@ewr3243 如果使用 C++17 或更高版本,则:
inline static unsigned int ct;