[問題] struct static const member link error

看板C_and_CPP作者 (lionking - 辛巴)時間10年前 (2015/01/21 03:16), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Ubuntu 14.04, g++ v4.8.2 問題(Question): link error, undefined reference to XXX 程式碼(Code):(請善用置底文網頁, 記得排版) 問題程式碼如下,分在兩個檔案 [fileA.h] struct A { static const int val = 0; }; [fileB.cpp] /* something */ std::unordered_map<int, std::string> umap; /* somthing */ const std::string str = umap.at(A::val) + "123"; // error here 上面那行就是我的問題所在 因為 A::val 是 A 的 static const member,所以語法上應該是沒問題的 compile 也確實有過,但是 link 時就噴 error 說找不到 A::val 後來我把 fileB.cpp 的那一段改成下面這樣就過了: [fileB.cpp] /* something */ std::unordered_map<int, std::string> umap; /* something */ const int VAL = A::val; const std::string str = umap.at(VAL) + "123"; // pass 我想不出原因為什麼一開始的寫法會 link error 但是改成下面這種寫法就過了 想請問有版友知道原因嗎? 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.6.159 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1421810188.A.919.html
文章代碼(AID): #1KlneCaP (C_and_CPP)
文章代碼(AID): #1KlneCaP (C_and_CPP)