C++运算符重载怎么实现行列式的加减

   2025-02-04 4980
核心提示:要实现行列式的加减运算,你需要重载加法运算符和减法运算符。下面是一个示例代码:#include iostream#include vectorclass Matr

要实现行列式的加减运算,你需要重载加法运算符和减法运算符。下面是一个示例代码:

#include <iostream>#include <vector>class Matrix {private:    int rows;    int cols;    std::vector<std::vector<int>> data;public:    Matrix(int r, int c) : rows(r), cols(c) {        data.resize(rows, std::vector<int>(cols, 0));    }    void setValue(int r, int c, int value) {        data[r][c] = value;    }    Matrix operator+(const Matrix& other) const {        if (rows != other.rows || cols != other.cols) {            throw std::runtime_error("Matrix dimensions don't match");        }        Matrix result(rows, cols);        for (int i = 0; i < rows; i++) {            for (int j = 0; j < cols; j++) {                result.data[i][j] = data[i][j] + other.data[i][j];            }        }        return result;    }    Matrix operator-(const Matrix& other) const {        if (rows != other.rows || cols != other.cols) {            throw std::runtime_error("Matrix dimensions don't match");        }        Matrix result(rows, cols);        for (int i = 0; i < rows; i++) {            for (int j = 0; j < cols; j++) {                result.data[i][j] = data[i][j] - other.data[i][j];            }        }        return result;    }    void print() const {        for (int i = 0; i < rows; i++) {            for (int j = 0; j < cols; j++) {                std::cout << data[i][j] << " ";            }            std::cout << std::endl;        }    }};int main() {    Matrix A(2, 2);    A.setValue(0, 0, 1);    A.setValue(0, 1, 2);    A.setValue(1, 0, 3);    A.setValue(1, 1, 4);    Matrix B(2, 2);    B.setValue(0, 0, 5);    B.setValue(0, 1, 6);    B.setValue(1, 0, 7);    B.setValue(1, 1, 8);    Matrix C = A + B;    C.print();    std::cout << std::endl;    Matrix D = A - B;    D.print();    return 0;}

在上面的代码中,我们定义了一个 Matrix 类来表示行列式。在 Matrix 类中,我们重载了加法运算符和减法运算符,使其能够对两个 Matrix 对象进行对应元素的加减操作。在重载的加法和减法运算符函数中,我们首先检查两个 Matrix 对象的维度是否相同,如果不相同,则抛出异常。然后,我们创建一个新的 Matrix 对象来存储结果,并通过遍历每个元素,对应相加或相减。最后,返回结果 Matrix 对象。

在主函数中,我们创建了两个 Matrix 对象 A 和 B,并分别对其进行赋值。然后,我们使用重载的加法运算符和减法运算符来计算 A + B 和 A - B,并将结果打印出来。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言