Fuq*_*han 3 c++ arrays size constants
我想要完成的是:
inline const int size() { return 256; }
int main()
{
int arr[size()];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是 Visual Studio 在初始化 arr[size()] 时给了我一个错误:
表达式必须有一个常量值
有没有办法在不使用全局变量、宏、std::vector 或在堆上创建 arr[] 的情况下完成我想要的?
删除inlineandconst并添加constexpr说明符,以解决问题:
constexpr int size() { return 256; }
Run Code Online (Sandbox Code Playgroud)
现在您可以将其用作数组大小,例如:
int arr[size()];
Run Code Online (Sandbox Code Playgroud)
在 C++(不是 C)中,必须在编译时知道数组的长度。const限定符仅表示在程序运行期间不得更改值。
通过使用,constexpr您将指定函数的输出是一个已知常量,甚至在程序执行之前也是如此。
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |