【发布时间】:2023-04-08 14:02:02
【问题描述】:
在研究 C++ 中的 constexpr 关键字时,我想出了以下代码:
#include <iostream>
int main() {
const int n = 10;
constexpr int n2 = 10;
int a1[n];
int a2[n2];
std::cout << "n " << n << std::endl;
std::cout << "n2 " << n2 << std::endl;
}
我希望用“const”声明数组 a1 不起作用,编译器至少会给我一个警告(假设编译是用 g++ -Wall -pedantic constexpr_1.cpp -o ce1 完成的)但它确实不是。我在 VS 编译器中看到了一些错误,所以这里欢迎任何提示。
【问题讨论】:
-
数组的大小必须在编译时知道,
n和n2在编译时是已知的,不能在运行时修改,至少不能以合法的方式修改。也许this question 对你来说很有趣。