对静态变量 Foo::a 的未定义引用?
我收到此错误,但我不知道这意味着什么:
$ mingw32-g++ Test.cpp -o Test.exe
C:\Documents and Settings\BDL\ccksiYhI.o:Test.cpp:(.text+0x11): undefined reference to 'Foo::a'
collect2: ld returned 1 exit status
这是我的代码。
Test.cpp
#include <vector>
#include "Test.h"
int main() {
Foo::a.clear();
return 0;
}
Test.h
#include <vector>
class Foo {
public:
static std::vector<int> a;
};
这不是我的原始代码,但我已将其归结为这个问题。我是 C++ 新手,如果有人能解释为什么这是错误的以及我如何解决它,我将不胜感激。
I am getting this error and I have no idea what it means:
$ mingw32-g++ Test.cpp -o Test.exe
C:\Documents and Settings\BDL\ccksiYhI.o:Test.cpp:(.text+0x11): undefined reference to 'Foo::a'
collect2: ld returned 1 exit status
This is my code.
Test.cpp
#include <vector>
#include "Test.h"
int main() {
Foo::a.clear();
return 0;
}
Test.h
#include <vector>
class Foo {
public:
static std::vector<int> a;
};
This isn't my original code but I have boiled it down to this problem. I am new to c++ and if anyone can explain why this is wrong and how I can work around it I would appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您仍然需要定义成员变量,即使它是静态的。将您的 Test.cpp 更改为:
You still need to define the member variable, even if it's static. Change your Test.cpp to this:
您还需要在一个翻译单元中定义静态成员,例如在
Test.cpp
中:You need to define static members as well in one translation unit, e.g. in
Test.cpp
:静态成员必须在类外部定义。里面有一份声明。
网上有很多网站都有示例。搜索“定义 C++ 静态成员”。
祝你好运,欢迎来到 SO。
Static members must be defined outside the class. Inside you have a declaration.
There are many sites online with examples. Search for "define C++ static members."
Good luck with it and welcome to SO.