我通過鏈接錯誤使用下面的代碼時,百思不得其解(未定義參考):「靜態const int的」鏈接會導致錯誤
// static_const.cpp -- complete code
#include <vector>
struct Elem {
static const int value = 0;
};
int main(int argc, char *argv[]) {
std::vector<Elem> v(1);
std::vector<Elem>::iterator it;
it = v.begin();
return it->value;
}
然而,這種連接失敗時 - 不知它需要有一個符號爲靜態常量「值」。
$ g++ static_const.cpp
/tmp/ccZTyfe7.o: In function `main':
static_const.cpp:(.text+0x8e): undefined reference to `Elem::value'
collect2: ld returned 1 exit status
順便說一句,這個編譯好-O1或更好;但對於更復雜的情況仍然失敗。我使用的是gcc 4.4.4版本20100726(Red Hat 4.4.4-13)。
任何想法可能是我的代碼有問題嗎?
[結構/類中的奇怪的未定義的靜態常量符號]重複(http://stackoverflow.com/questions/4891067/weird-undefined-symbols-of-static-constants-inside-a-struct-類) – karlphillip 2011-04-01 01:22:52
感謝您的有用鏈接!它還顯示了一個替代解決方案,'struct Elem {enum {value = 0}; '',這看起來很有吸引力。 – hrr 2011-04-01 01:45:28
[C++ - 在類定義中定義靜態常量整型成員]的可能重複(http://stackoverflow.com/questions/3025997/c-defining-static-const-integer-members-in-class-definition) – ks1322 2014-03-11 08:52:42