类中的静态成员变量

use*_*769 1 c++ static class

可能重复:
什么是未定义的引用/未解析的外部符号错误,如何解决?

为什么我Monitor::count对以下代码有"未定义的引用"错误?谢谢!

#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;
}
Run Code Online (Sandbox Code Playgroud)

ild*_*arn 10

因为你声明它但不定义它.将以下内容放在一个(也是唯一一个).cpp文件中:

int Monitor::count = 0;
Run Code Online (Sandbox Code Playgroud)

  • @ user673769:是的,§8.5/ 6保证所有静态对象都至少为零初始化.因此,如果需要,可以将定义缩短为"int Monitor :: count;",但无论如何都需要定义. (2认同)