开发者

static member variable in a class [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

What is an undefined reference/unresolved external symbol error and how do I fix it?

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 functi开发者_开发技巧on 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;
}


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;


You have not defined the static variable count.

class Monitor
{
     // ...
};

int Monitor::count = 0 ;

// ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜