【问题标题】:initialize map with static member variable使用静态成员变量初始化映射
【发布时间】:2015-09-28 00:11:45
【问题描述】:

我不明白为什么我不能在映射的初始化列表(可能是任何容器)中使用类的公共 const 静态成员。据我了解,“MyClass::A”是一个右值,看起来它应该与我使用“THING”的情况完全相同,“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 上使用 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

【问题讨论】:

  • 应该可以。请参阅:ideone.com/TuNTeV 您使用的是什么编译器?传递--std=c++11 标志?
  • 我不知道ideone.com,我真的应该考虑使用在线ide来仔细检查这种奇怪的情况。谢谢

标签: c++ static


【解决方案1】:

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

【讨论】:

  • 这确实有效,同时这现在感觉像是一个错误(在clang中)地图初始化程序不应该在这里尝试引用,也许是右值引用,但我仍然有点对这些一无所知。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多