c++ 将 2D 数组分配给对象

c++ assign a 2D array to an Object

本文关键字:对象 分配 数组 2D c++      更新时间:2023-10-16

我的代码通过了编译器,但我对指针的概念有疑问。

主.cpp:

int main(int argc, const char * argv[])
{
    int inputPuzzle[3][3];
    std::cout << "Set the puzzle: " << "n";
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            std::cin >> inputPuzzle[i][j];
        }
    }
    puzzle puzzle_1 = *new puzzle(inputPuzzle);
    puzzle_1.display();
    return 0;
}

拼图.h:

class puzzle
{
    public:
        puzzle();
        puzzle(int [][maxCol]);
        ~puzzle();
    public:
        int puzz [maxRow][maxCol];
};

拼图.cpp:

puzzle::puzzle(int a[][maxCol])
{
    for (int i = 0; i < maxRow; i++) {
        for (int j = 0; j < maxCol; j++) {
            puzz[i][j] = a[i][j];
        }
    }
}

我的问题是关于声明的:puzzle puzzle_1 = *new puzzle(inputPuzzle);

为什么我必须在要在其中分配 2D 数组的新对象前面添加"*"?

您正在C++编程,其中new返回一个指针。当你使用星号时,它是取消引用运算符,基本上将指针变成非指针。

像这样使用 取消引用运算符意味着您实际上会丢失 new 创建的指针,并且您无法释放分配的内存delete这当然会导致内存泄漏。

为了避免丢失指针,您必须将变量声明为指针:

puzzle* puzzle_1 = new puzzle(inputPuzzle);

然后,在访问成员时,您必须改用指针成员选择器运算符:

puzzle_1->display();

而且,为了避免泄漏内存,当您完成指针时,您必须delete它:

delete puzzle_1;

但是,在C++中,很少需要使用指针;而只是将其声明为普通变量:

puzzle puzzle_1(inputPuzzle);
puzzle_1.display();

与您的问题无关,但如果maxRowmaxCol大于 3 ,那么您将从内存外部读取数组inputPuzzle。这将导致未定义的行为

这里最重要的部分是new关键字。它返回指向新实例化对象的指针。检查动态内存分配以获取更多信息,并了解何时以及如何使用指针,以及 new 关键字的工作原理。

现在,我们知道 new 关键字返回一个指针,并且您希望获取一个对象而不是指针,因此您必须取消引用您的指针。

现在有两个正确的解决方案:

// without pointers
puzzle puzzle_1(inputPuzzle); // initialize the object without going through a copy 
puzzle_1.display();
// with pointers
puzzle *puzzle_1 = new puzzle(inputPuzzle);
puzzle_1->display(); //notice that we used -> here as it's a pointer
// do stuffs here
delete puzzle_1; // free the memory