2015-09-28 67 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