D语言数组定义报错: 变量作为数组容量的解决方法
D语言数组定义报错: 变量作为数组容量的解决方法
在D语言中,数组的大小必须是在编译时确定的常量。以下代码中,变量'd'是在运行时才能确定其值,因此无法在数组定义中使用。
import std.stdio;
void main()
{
int d = 'hello'.length;
int[d] arr = [1,2,3,4,5];
writeln(arr);
}
编译出错:
a_变量作为数组容量去定义.d(6): Error: variable `d` cannot be read at compile time
解决方案1:将数组大小改为常量
import std.stdio;
void main()
{
const d = 'hello'.length;
int[d] arr = [1,2,3,4,5];
writeln(arr);
}
在这个解决方案中,我们将变量'd'改为了常量,因此可以在数组定义中使用。
解决方案2:使用动态数组
import std.stdio;
void main()
{
int[] arr = [1,2,3,4,5];
writeln(arr);
}
在这个解决方案中,我们使用了动态数组,不需要在定义时指定数组的大小。
原文地址: http://www.cveoy.top/t/topic/oljy 著作权归作者所有。请勿转载和采集!