[问题] 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