static member variable in a class [duplicate]
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 ;
// ...
精彩评论