我想创建一个常量和静态整数数组作为公共类变量。定义它并立即初始化它是很巧妙的。有关完整的示例,请参阅下面的代码。
#include <iostream>
class Foo {
public:
constexpr static int arr[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
};
int main() {
for (int i = 0; i < 3; i++) {
std::cout << "Pair " << Foo::arr[i][0] << ", " << Foo::arr[i][1] << std::endl;
}
return 0;
}
但是,使用g++ --std=c++11 test.cpp
编译上面的代码会产生
/usr/bin/ld: /tmp/ccc7DFI5.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Foo::arr'
/usr/bin/ld: test.cpp:(.text+0x55): undefined reference to `Foo::arr'
collect2: error: ld returned 1 exit status
这在C++中是不可能的吗?更有可能的是,我遗漏了一些关于C++及其静态变量初始化策略的内容。
发布于 2021-03-01 04:05:56
在C++17 (如C++11和C++14)之前,您必须添加
constexpr int Foo::arr[3][2];
在类的主体之外。
发布于 2021-03-01 04:00:01
编译器错误是由于C++11
标准造成的。
通过编译上面的代码来使用C++17
标准
g++ --std=c++17 test.cpp
不会产生错误。
编辑:这个解决方案适用于C++17
,而不是我最初提出的问题中的C++11
。有关C++11
解决方案,请参阅接受的答案。
https://stackoverflow.com/questions/66413131
复制相似问题