这是一个C ++编程代码,用于显示array1和array2的值,但出现编译时错误,提示“需要常量表达式”。请帮忙
void display(const int const1 = 5)
{
const int const2 = 5;
int array1[const1];
int array2[const2];
for(int i = 1 ; i < 5 ; i++)
{
array1[i] = i;
array2[i] = i * 10;
std::cout << array1[i] << std::endl;
}
}
void main()
{
display(5);
}
在C ++中,const
并不总是constexpr
。在过去,它constexpr
不存在,因此拥有编译时间常数的唯一方法是const
与文字一起使用enum
,或使用,因为这两种编译器都易于检查值。
但是,在C ++ 11中,我们添加了constexpr
,它保证constexpr
变量在编译时具有可用的值,并且声明constexpr
如果所有参数也都可以在编译时对函数进行求值constexpr
。
在代码中,您可以这样编写变量const2
:
void display(const int const1=5)
{
constexpr int const2 = 5;
// ...
}
现在,您的代码对您正在做的事情更具表现力。而不是说const可能在编译时可用,而是说“此变量在编译时有一个已知值,这里是值”。
但是,如果尝试更改const1
,则会出现错误。参数,即使具有默认值,也始终是运行时已知的值。如果仅在运行时知道该值,则不能在模板参数或数组大小中使用它。
如果您希望函数能够receive
将值const1
作为一个常量表达式,从那里可以将其作为模板参数接收,因为模板参数总是在编译时就知道的。
template<int const1 = 5>
void display()
{
constexpr int const2 = 5;
int array1[const1];
int array2[const2];
}
您将必须像这样调用函数:
// const1 is 5
display();
// const1 is 10
display<10>();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句