Warm tip: This article is reproduced from serverfault.com, please click

c++-未定义对静态类成员的引用

(c++ - Undefined reference to static class member)

发布于 2008-11-07 17:39:56

谁能解释为什么以下代码无法编译?至少在g ++ 4.2.4上。

更有趣的是,当我将MEMBER转换为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;
}
Questioner
Pawel Piatkowski
Viewed
0
Drew Hall 2014-01-05 05:37:26

你实际上需要在某个地方(在类定义之后)定义静态成员。尝试这个:

class Foo { /* ... */ };

const int Foo::MEMBER;

int main() { /* ... */ }

那应该摆脱未定义的参考。