在C++中實現(xiàn)矩陣類的加減乘除,首先需要創(chuàng)建一個矩陣類(Matrix),然后為該類定義加減乘除的運算符重載函數(shù)。以下是一個簡單的示例:
#include<iostream>
#include<vector>
class Matrix {
public:
Matrix(int rows, int cols) : rows_(rows), cols_(cols), data_(rows * cols, 0) {}
// 獲取矩陣的行數(shù)
int rows() const { return rows_; }
// 獲取矩陣的列數(shù)
int cols() const { return cols_; }
// 獲取矩陣中指定位置的元素
double& operator()(int row, int col) {
return data_[row * cols_ + col];
}
// 獲取矩陣中指定位置的元素(常量版本)
double operator()(int row, int col) const {
return data_[row * cols_ + col];
}
// 矩陣加法
Matrix operator+(const Matrix& other) const;
// 矩陣減法
Matrix operator-(const Matrix& other) const;
// 矩陣乘法
Matrix operator*(const Matrix& other) const;
private:
int rows_;
int cols_;
std::vector<double> data_;
};
// 矩陣加法
Matrix Matrix::operator+(const Matrix& other) const {
if (rows_ != other.rows() || cols_ != other.cols()) {
throw std::invalid_argument("Matrix dimensions do not match for addition.");
}
Matrix result(rows_, cols_);
for (int i = 0; i< rows_; ++i) {
for (int j = 0; j< cols_; ++j) {
result(i, j) = (*this)(i, j) + other(i, j);
}
}
return result;
}
// 矩陣減法
Matrix Matrix::operator-(const Matrix& other) const {
if (rows_ != other.rows() || cols_ != other.cols()) {
throw std::invalid_argument("Matrix dimensions do not match for subtraction.");
}
Matrix result(rows_, cols_);
for (int i = 0; i< rows_; ++i) {
for (int j = 0; j< cols_; ++j) {
result(i, j) = (*this)(i, j) - other(i, j);
}
}
return result;
}
// 矩陣乘法
Matrix Matrix::operator*(const Matrix& other) const {
if (cols_ != other.rows()) {
throw std::invalid_argument("Matrix dimensions do not match for multiplication.");
}
Matrix result(rows_, other.cols());
for (int i = 0; i< rows_; ++i) {
for (int j = 0; j< other.cols(); ++j) {
for (int k = 0; k< cols_; ++k) {
result(i, j) += (*this)(i, k) * other(k, j);
}
}
}
return result;
}
int main() {
// 示例:創(chuàng)建兩個矩陣并進行加減乘除運算
Matrix A(2, 2);
Matrix B(2, 2);
A(0, 0) = 1; A(0, 1) = 2;
A(1, 0) = 3; A(1, 1) = 4;
B(0, 0) = 5; B(0, 1) = 6;
B(1, 0) = 7; B(1, 1) = 8;
Matrix C = A + B;
Matrix D = A - B;
Matrix E = A * B;
// 輸出結(jié)果
std::cout << "A + B:\n";
for (int i = 0; i < C.rows(); ++i) {
for (int j = 0; j < C.cols(); ++j) {
std::cout << C(i, j) << " ";
}
std::cout<< std::endl;
}
std::cout << "A - B:\n";
for (int i = 0; i < D.rows(); ++i) {
for (int j = 0; j < D.cols(); ++j) {
std::cout << D(i, j) << " ";
}
std::cout<< std::endl;
}
std::cout << "A * B:\n";
for (int i = 0; i < E.rows(); ++i) {
for (int j = 0; j < E.cols(); ++j) {
std::cout << E(i, j) << " ";
}
std::cout<< std::endl;
}
return 0;
}
這個示例中,我們創(chuàng)建了一個名為Matrix
的矩陣類,并為其定義了加減乘除的運算符重載函數(shù)。在main
函數(shù)中,我們創(chuàng)建了兩個矩陣并進行了加減乘除運算,最后將結(jié)果輸出到控制臺。