静态变量和函数的使用
我有以下类定义和 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),错误也是相同的。预先感谢您的帮助。
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): 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
The error is same even if I use c.send(1) instead of test::send(1). Thanks in advance for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已声明
test::a
,但尚未定义它。在命名空间范围中添加定义:You've declared
test::a
, but you haven't defined it. Add the definition in namespace scope:a 已声明,但仍必须定义。
http://www.parashift.com/c++-faq-lite /ctors.html#faq-10.12
a is declared but must still be defined.
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12