[問題] struct static const member link error

作者: shininglion (lionking - 辛巴)   2015-01-21 11:16:25
開發平台(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
但是改成下面這種寫法就過了
想請問有版友知道原因嗎?
謝謝!

Links booklink

Contact Us: admin [ a t ] ucptt.com