MST

星途 面试题库

面试题:C++ 类运算符重载之复合赋值运算符重载

假设有一个C++类 `Matrix` 表示二维矩阵,有成员变量 `rows`、`cols` 和一个动态分配的二维数组 `data` 用于存储矩阵元素。请重载 `+=` 运算符,实现将一个 `Matrix` 对象加到当前 `Matrix` 对象上。注意要处理矩阵维度不匹配的情况,并确保内存管理的正确性。请给出类的部分定义(包含成员变量和必要的构造函数、析构函数声明)以及 `+=` 运算符重载函数的实现。
49.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <stdexcept>

class Matrix {
private:
    int rows;
    int cols;
    double** data;

public:
    // 构造函数
    Matrix(int r, int c) : rows(r), cols(c) {
        data = new double* [rows];
        for (int i = 0; i < rows; ++i) {
            data[i] = new double[cols];
            for (int j = 0; j < cols; ++j) {
                data[i][j] = 0.0;
            }
        }
    }

    // 析构函数
    ~Matrix() {
        for (int i = 0; i < rows; ++i) {
            delete[] data[i];
        }
        delete[] data;
    }

    // += 运算符重载
    Matrix& operator+=(const Matrix& other) {
        if (rows != other.rows || cols != other.cols) {
            throw std::invalid_argument("Matrices must have the same dimensions");
        }
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                data[i][j] += other.data[i][j];
            }
        }
        return *this;
    }
};