对静态类成员的未定义引用 [英] Undefined reference to static class member
本文介绍了对静态类成员的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以解释为什么下面的代码不会编译?至少在g ++ 4.2.4上。
Can anyone explain why following code won't compile? At least on g++ 4.2.4.
更有趣的是,为什么当我将MEMBER转换为int时会进行编译?
And more interesting, why it will compile when I cast MEMBER to int?
#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
推荐答案
静态成员在某处(在类定义之后)。试试这个:
You need to actually define the static member somewhere (after the class definition). Try this:
class Foo { /* ... */ };
const int Foo::MEMBER;
int main() { /* ... */ }
这应该摆脱未定义的引用。
That should get rid of the undefined reference.
这篇关于对静态类成员的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文