arrays - 错误 : range violation in D programming

标签 arrays d

我在结构中有动态数组和使用动态数组的方法。问题是当我运行程序时出现范围冲突错误。但是,当我在方法中创建一个新的动态数组时,它工作正常。以下代码导致问题。

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/

相关文章:

java - 调整数组大小时出现空指针异常

c - 如何动态分配一个二维指针数组? (C)

arrays - Node +蒙戈: adding record to array inside collection

java - 修改公共(public)静态最终数组

d - 垃圾回收期间从析构函数传递的消息

performance - 如何并行化小型纯函数?

arrays - 如何在 bash 数组中存储命令返回值

immutability - 如何创建对不可变类的可重新分配引用?

d - 检查是否从类型构造函数创建了完整类型

import - 如何仅在 D 中导入包来扩展结构?