我想创建一个常量和静态整数数组作为公共类变量。定义它并立即初始化它是很好的。有关完整示例,请参阅下面的代码。
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,使用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
Run Code Online (Sandbox Code Playgroud)
这在 C++ 中是不可能的吗?我更有可能遗漏了有关 C++ 及其静态变量初始化策略的某些部分。
在 C++17(所以 C++11 和 C++14)之前,你必须添加
constexpr int Foo::arr[3][2];
Run Code Online (Sandbox Code Playgroud)
在课堂之外。
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |