我在结构中有动态数组和使用动态数组的方法。问题是当我运行程序时出现范围冲突错误。但是,当我在方法中创建一个新的动态数组时,它工作正常。以下代码导致问题。
struct MyStr {
int[] frontArr;
this(int max = 10) {
frontArr = new int[10];
}
void push(int x) {
frontArr[0] = x;
}
}
void main() {
MyStr s;
s.push(5);
}
但是,这个有效;
struct MyStr {
int[] frontArr;
this(int max = 10) {
frontArr = new int[10];
}
void push(int x) {
frontArr = new int[10]; // <---Add this line
frontArr[0] = x;
}
}
void main() {
MyStr s;
s.push(5);
}
我基本上添加了该行来测试范围。似乎在 push(int x) 方法中看不到初始化的 FrontArr。有什么解释吗?
提前致谢。
最佳答案
必须保证结构的初始化。这是您不希望结构的默认构造引发异常。出于这个原因,D 不支持结构中的默认构造函数。想象一下如果
MyStr s;
导致抛出异常。相反,D 提供了自己的默认构造函数,它将所有字段初始化为 init 属性。在你的情况下,你没有调用你的构造函数,只是使用提供的默认值,这意味着 frontArr 永远不会被初始化。你想要这样的东西:
void main() {
MyStr s = MyStr(10);
s.push(5);
}
为 struct 构造函数的所有参数设置默认值可能应该是编译器错误。 Bugzilla
关于arrays - 错误 : range violation in D programming,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4341475/