0

我有以下类定义和 main()。有人可以指出我为什么会收到错误吗?

#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;
}

我得到的错误如下:

/tmp/ccre4um4.o: In function `test::test()':
test_static.cpp:(.text._ZN4testC1Ev[test::test()]+0x1b): undefined 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

即使我使用 c.send(1) 而不是 test::send(1),错误也是一样的。在此先感谢您的帮助。

4

2 回答 2

6

你已经声明 test::a了,但你还没有定义它。在命名空间范围内添加定义:

list<int> test::a;
于 2011-05-31T21:38:06.480 回答
1

a 已声明,但仍必须定义。 http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12

于 2011-05-31T21:41:03.767 回答