如何重载赋值运算符并为二维动态数组创建复制构造函数?

How to overload assignment operator and create copy constructor for 2D Dynamic Arrays?

我有一个航班 class,里面有 bool** 属性。

class Flight {
public:
 int flightNumber;
 int row;
 int seat;
 bool** seatReserv;
 Flight();
 Flight(int fly,int rw,int st);
 ~Flight();
 Flight(const Flight& rightVal);
 Flight& operator=(const Flight& rightVal);
 };

我尝试如下编写我的重载赋值运算符,但我意识到即使我更改了我的行和座位 属性,我也没有更改二维数组 [行] 和 [座位] 的大小。

Flight& Flight::operator=(const Flight& rightVal){
        if(this != &rightVal){
                for(int i = 0; i < row; i++){
                    delete[] this->seatReserv[i];
                }
                delete [] this->seatReserv;


            flightNumber = rightVal.flightNumber;
            row = rightVal.row;
            seat = rightVal.seat;



            this -> seatReserv = new bool*[row];
            for(int i = 0; i < row; i++){
                seatReserv[i] = new bool[seat];

            }

            for(int i = 0; i < row; i++){
                for(int j = 0; j < seat; j++){
                    seatReserv[i][j] = rightVal.seatReserv[i][j];

                }
            }


        }

        return *this;

        }

此外,我在下面的复制构造函数中遇到了同样的问题,所以问题是我如何编写复制构造函数并为我的 class 重载赋值运算符?

Flight::Flight(const Flight& rightVal){
        flightNumber = rightVal.flightNumber;
        row = rightVal.row;
        seat = rightVal.seat;
        for(int i = 0; i < row; i++){
            for(int j = 0; j < seat; j++){
                seatReserv[i][j] = rightVal.seatReserv[i][j];
            }
        }
    }

编辑:我不能使用矢量,这是为了家庭作业,所以禁止使用矢量。

这个

       this -> seatReserv = new bool*[row];
        for(int i = 0; i < row; i++){
            seatReserv[i] = new bool[i];

        }

应该是这个

       this -> seatReserv = new bool*[row];
        for(int i = 0; i < row; i++){
            seatReserv[i] = new bool[seat];

        }

细节很重要。

您的复制构造函数没有为您的二维数组分配任何内存,所以这是个问题。

这可能会用作复制构造函数:

Flight::Flight(const Flight &rightVal){
    this->flightNumber = rightVal.flightNumber;
    this->row = rightVal.row;
    this->seat = rightVal.seat;
    this->seatReserv = new bool*[row];
    for (int i = 0; i < this->row; i++){
        this->seatReserv[i] = new bool[seat];
        for (int j = 0; j < this->seat; j++){
            this->seatReserv[i][j] = rightVal.seatReserv[i][j];
        }
    }
}

对于 = 运算符,您可能使用与上面相同的东西,但不要忘记在使用析构函数之前删除那里的内容(这是为了避免内存泄漏)。

Flight::~Flight(){
    if (seatReserv == nullptr) return; //this means that at the beginning of the class seatReserv should be set to nullptr.

    for (int i = 0; i < this->row; i++){
        delete[] seatReserv[i];
    }
    delete[] seatReserv;
}

我还建议不要使用“二维数组”,而是使用长度为 row * seat 的单个布尔序列。要在特定位置访问一个,您可以这样做: i * row + j,而不是这个 array[i][j].

分配和释放时速度更快,CPU 缓存效率更高。