简体   繁体   English

使用静态成员变量初始化map

[英]initialize map with static member variable

I do not understand why I cannot use a public const static member of a class in the initializer list of a map (probably any container). 我不明白为什么我不能在地图的初始化列表中使用类的公共const静态成员(可能是任何容器)。 As I understand it "MyClass::A" is an rvalue, it seems like it should be the exact same as the case where I am using "THING" which is also a static const just outside of a class. 据我所知,“MyClass :: A”是一个右值,看起来它应该与我使用“THING”的情况完全相同,它也是一个类外的静态const。

Here is the error: 这是错误:

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)

And here is the code: 以下是代码:

#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;
}

UPDATE 1: 更新1:

Using clang on OS X: 在OS X上使用clang:

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

compiler flags: 编译器标志:

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

Something in the map code probably tried to take the address of a reference to your int. 地图代码中的某些内容可能试图获取对int的引用的地址。

The class definition here: 这里的类定义:

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

does not actually create any memory for A . 实际上并没有为A创建任何内存。 In order to do that you have to do in the header file: 为了做到这一点,你必须在头文件中做:

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

and in a CPP file: 并在CPP文件中:

const int MyClass::A = 1;

Or I guess with the newest C++ versions you can leave the = 1 in the header and just declare the storage in the CPP file with: 或者我想在最新的C ++版本中,您可以在标题中保留= 1 ,只需在CPP文件中声明存储:

const int MyClass::A;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM