繁体   English   中英

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

[英]initialize map with static member variable

我不明白为什么我不能在地图的初始化列表中使用类的公共const静态成员(可能是任何容器)。 据我所知,“MyClass :: A”是一个右值,看起来它应该与我使用“THING”的情况完全相同,它也是一个类外的静态const。

这是错误:

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上使用clang:

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

地图代码中的某些内容可能试图获取对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;

暂无
暂无

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

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