类中的静态成员变量 [英] static member variable in a class
本文介绍了类中的静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我有一个未定义的引用 Monitor :: count
错误为以下代码?谢谢!
Why do I have a "undefined reference to Monitor::count
" error for the following code? Thanks!
#include <iostream>
using namespace std;
class Monitor
{
static int count;
public:
void print() { cout << "incident function has been called " << count << " times" << endl; }
void incident() { cout << "function incident called" << endl; count++; }
};
void callMonitor()
{
static Monitor fooMonitor;
fooMonitor.incident();
fooMonitor.print();
}
int main()
{
for (int i = 0; i < 5; i++)
callMonitor();
return 1;
}
推荐答案
但不要定义。将以下内容放在一个(和仅一个).cpp文件中:
Because you declare it but do not define it. Put the following in one (and only one) of your .cpp files:
int Monitor::count = 0;
这篇关于类中的静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文