【问题标题】:static member variable in a class [duplicate]类中的静态成员变量[重复]
【发布时间】:2011-04-08 21:40:41
【问题描述】:

可能重复:
What is an undefined reference/unresolved external symbol error and how do I fix it?

为什么以下代码出现“未定义对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;
}

【问题讨论】:

    标签: c++ class static


    【解决方案1】:

    因为您声明它但不定义它。将以下内容放入您的一个(并且一个).cpp 文件中:

    int Monitor::count = 0;
    

    【讨论】:

    • 静态变量不是默认初始化为0吗?
    • @user673769 :是的,第 8.5/6 节保证所有静态对象将至少为零初始化。因此,您可以根据需要将定义缩短为 int Monitor::count;,但无论哪种方式都需要定义。
    【解决方案2】:

    您尚未定义静态变量count

    class Monitor
    {
         // ...
    };
    
    int Monitor::count = 0 ;
    
    // ...
    

    【讨论】:

    • @ildjarn - 我对编程术语的使用感到震惊:)
    • 别担心,我只是学究气。 ;-]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多