有两个矩阵a和b,均为2行3列。求两个矩阵之和,重载运算符“+”,使之能用于矩阵相加。如c=a+b。,重载插入运算符”<<”和流提取运算符“>>”,使之能用于该矩阵的输入和输出。
时间: 2024-02-11 20:07:56 浏览: 78
两矩阵相加
好的,这是一个关于C++中矩阵运算符重载的问题。下面是一份可能的代码实现:
```c++
#include <iostream>
class Matrix {
private:
int row, col;
int **data;
public:
Matrix(int row, int col) {
this->row = row;
this->col = col;
data = new int*[row];
for (int i = 0; i < row; i++) {
data[i] = new int[col];
}
}
Matrix(const Matrix& other) {
row = other.row;
col = other.col;
data = new int*[row];
for (int i = 0; i < row; i++) {
data[i] = new int[col];
for (int j = 0; j < col; j++) {
data[i][j] = other.data[i][j];
}
}
}
~Matrix() {
for (int i = 0; i < row; i++) {
delete[] data[i];
}
delete[] data;
}
Matrix operator+(const Matrix& other) const {
if (row != other.row || col != other.col) {
throw std::invalid_argument("Matrix dimensions do not match.");
}
Matrix result(row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix& matrix) {
for (int i = 0; i < matrix.row; i++) {
for (int j = 0; j < matrix.col; j++) {
os << matrix.data[i][j] << " ";
}
os << std::endl;
}
return os;
}
friend std::istream& operator>>(std::istream& is, Matrix& matrix) {
for (int i = 0; i < matrix.row; i++) {
for (int j = 0; j < matrix.col; j++) {
is >> matrix.data[i][j];
}
}
return is;
}
};
int main() {
Matrix a(2, 3);
Matrix b(2, 3);
std::cout << "Enter matrix a:" << std::endl;
std::cin >> a;
std::cout << "Enter matrix b:" << std::endl;
std::cin >> b;
Matrix c = a + b;
std::cout << "a + b = " << std::endl << c;
return 0;
}
```
这份代码定义了一个`Matrix`类,其中包含矩阵的行数、列数和矩阵数据。重载了运算符`+`使之能够进行矩阵加法,重载了运算符`<<`和`>>`使之能够进行输入和输出。在`main`函数中,我们首先定义了两个矩阵`a`和`b`,分别输入它们的值,然后进行加法运算,输出结果。
阅读全文