【问题标题】:C++, How to make a dynamically sized 2D array in object oriented programming?C++,如何在面向对象编程中制作动态大小的二维数组?
【发布时间】:2019-11-10 17:48:55
【问题描述】:

我目前正在使用 C++ 进行一些编程,但在尝试声明和初始化 int 类型的动态二维数组时遇到了很多麻烦。这应该是一个面向对象的程序,但我创建这种数组的唯一真实经验是将所有内容都放在一个文件中。

这是我目前的尝试,这是我的头文件中对象的类数据。 (没有 get/set 方法,因为这些方法与此问题无关。)

class SlidingPuzzle {

private:
    int height;
    int length;
    int** theBoard = NULL;

public:
    SlidingPuzzle(); 
    SlidingPuzzle(int, int); 
    ~SlidingPuzzle(); 
};

这是构造函数'SlidingPuzzle();'来自我的源文件

SlidingPuzzle::SlidingPuzzle() {
    this->height = 3;
    this->length = 3;
    this->theBoard = new(int*[this->height]);
    for (int i = 0; i < this->height; i++) {
        this->theBoard[i] = new(int[this->length]);
    }
    for (int i = 0; i < this->height; i++) {
        for (int j = 0; j < this->length; i++) {
            this->theBoard[i][j] = 0;
        }
    }
}

this-&gt;theBoard[i][j] = 0; 处抛出异常

我在这里有什么功能吗?还是我这样做完全错误?

这是我正在制作的程序的重要组成部分,如果不解决这个问题,我真的无法继续。

编辑:错误是一个小错字

for (int j = 0; j < this->length; i++) {
    this->theBoard[i][j] = 0;
}

不小心放了 i 而不是 j,导致超出范围,谢谢。

【问题讨论】:

标签: c++ arrays


【解决方案1】:

这个循环是错误的。

for (int j = 0; j < this->length; i++) {

你必须增加j,而不是i

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    相关资源
    最近更新 更多