我在struct中有动态数组,使用动态数组的方法.问题是我运行程序时出现范围违规错误.但是当我在方法中创建一个新的动态数组时,它工作正常.以下代码会导致问题.
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);
}
Run Code Online (Sandbox Code Playgroud)
但是,这一个有效;
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);
}
Run Code Online (Sandbox Code Playgroud)
我基本上添加该行来测试范围.似乎在push(int x)方法中看不到初始化的FrontArr.任何解释?
提前致谢.
必须保证结构的初始化.这是您不希望结构的默认构造抛出异常.因此,D不支持结构中的默认构造函数.想象一下,如果
MyStr s;
Run Code Online (Sandbox Code Playgroud)
导致异常被抛出.而是D提供了自己的默认构造函数,它将所有字段初始化为init属性.在你的情况下,你没有调用你的构造函数,只是使用提供的默认值,这意味着frontArr永远不会被初始化.你想要的东西:
void main() {
MyStr s = MyStr(10);
s.push(5);
}
Run Code Online (Sandbox Code Playgroud)
为结构构造函数的所有参数设置默认值应该是编译器错误.Bugzilla的