Static variables and functions usage
I have the following class definition and the main(). Can someone please point me why I am getting the error?
#include <iostream>
#include <list>
using namespace std;
class test
{
protected:
static list<int> a;
public:
test()
{
a.push_back(150);
}
static void send(int c)
{
if (c==1)
cout<<a.front()<<endl;
}
};
int main()
{
test c;
test::send(1);
return 0;
}
The error that I get is as follows:
/tmp/ccre4um4.o: In function `test::test()':
test_static.cpp:(.text._ZN4testC1Ev[test::test()]+0x1b): undefin开发者_Go百科ed reference to `test::a'
/tmp/ccre4um4.o: In function `test::send(int)':
test_static.cpp:(.text._ZN4test4sendEi[test::send(int)]+0x12): undefined reference to `test::a'
collect2: ld returned 1 exit status
The error is same even if I use c.send(1) instead of test::send(1). Thanks in advance for the help.
You've declared test::a
, but you haven't defined it. Add the definition in namespace scope:
list<int> test::a;
a is declared but must still be defined. http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12
精彩评论