gpt4 book ai didi

c++ - 使用静态成员变量初始化映射

转载 作者:太空狗 更新时间:2023-10-29 21:39:31 25 4
gpt4 key购买 nike

我不明白为什么我不能在映射(可能是任何容器)的初始化列表中使用类的公共(public)常量静态成员。据我所知,“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 上使用 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

最佳答案

map 代码中的某些内容可能试图获取对您的 int 的引用地址。

这里的类定义:

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

实际上并不为A 创建任何内存。为此,您必须在头文件中执行以下操作:

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

在 CPP 文件中:

const int MyClass::A = 1;

或者我想对于最新的 C++ 版本,您可以在 header 中保留 = 1 并仅在 CPP 文件中声明存储:

const int MyClass::A;

关于c++ - 使用静态成员变量初始化映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com