2015-09-28 71 views
3

我不明白爲什麼我無法在映射的初始化程序列表(可能是任何容器)中使用公共常量靜態成員。據我瞭解,「MyClass :: A」是一個右值,它看起來應該和我使用「THING」的情況完全相同,它也是一個類之外的靜態常量。使用靜態成員變量初始化映射

以下是錯誤:

Undefined symbols for architecture x86_64: 
    "MyClass::A", referenced from: 
     _main in map-380caf.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

這裏是代碼:

#include <iostream> 
#include <map> 
#include <string> 

static const int THING = 1; 

class MyClass { 
public: 
    static const int A = 1; 
}; 

int 
main() 
{ 
    int a; 
    typedef std::map<int, std::string> MyMap; 

    // compiles and works fine 
    a = MyClass::A; 
    std::cout << a << std::endl; 

    // compiles and works fine 
    MyMap other_map = { {THING, "foo"} }; 
    std::cout << other_map.size() << std::endl; 

    // Does not compile 
    MyMap my_map = { {MyClass::A, "foo"} }; 
    std::cout << my_map.size() << std::endl; 

    return 0; 
} 

更新1:

使用OS X上的鏗鏘:

Apple LLVM version 7.0.0 (clang-700.0.72) 
Target: x86_64-apple-darwin14.5.0 
Thread model: posix 

編譯器標誌:

clang++ map.cc -std=c++1y 
+0

應該工作。請參閱:http://ideone.com/TuNTeV您正在使用哪種編譯器?傳遞'--std = C++ 11'標誌? – Chad

+0

我不知道ideone.com,我真的應該考慮使用在線ide來仔細檢查這種奇怪的情況。謝謝 – user2466803

回答

2

地圖代碼中的某些東西可能試圖將地址引用到int中。

類定義在這裏:

class MyClass { 
public: 
    static const int A = 1; 
}; 

實際上並不爲A創建的任何記憶。爲了做到這一點,你必須在頭文件中要做到:

class MyClass { 
public: 
    static const int A; 
}; 

,並在CPP文件:

const int MyClass::A = 1; 

或者我想與最新的C++版本中,你可以離開= 1在頭只需在CPP文件中聲明存儲:

const int MyClass::A; 
+0

這確實奏效,同時現在感覺像是一個bug(在clang中)map初始化器不應該試圖在這裏引用一個引用,也許是一個右值引用,但我對這些仍然有點無知。 – user2466803