使用类与对象、运算符重载等知识点,实现矩阵类类型,并扩展适合于矩阵类型的+、-、*、/等运算功能。 本题中的矩阵是指一个按照长方阵列排列的实数集合,具有多行多列。由 m × n 个数aij排成的m行n列的数表称为m行n列的矩阵,简称m × n矩阵。记作
时间: 2024-04-02 14:32:20 浏览: 97
使用C++实现矩阵运算(运算符重载)
5星 · 资源好评率100%
class Matrix {
private:
int m, n; // 矩阵的行数和列数
vector<vector<double>> data; // 存储矩阵数据的二维数组
public:
Matrix(int row, int col) : m(row), n(col), data(row, vector<double>(col)) {}
// 获取矩阵的行数和列数
int row() const { return m; }
int col() const { return n; }
// 重载下标运算符
vector<double>& operator[](int i) { return data[i]; }
const vector<double>& operator[](int i) const { return data[i]; }
// 重载加法运算符
Matrix operator+(const Matrix& other) const {
if (m != other.m || n != other.n) {
throw invalid_argument("The dimensions of two matrices are different.");
}
Matrix res(m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[i][j] = data[i][j] + other[i][j];
}
}
return res;
}
// 重载减法运算符
Matrix operator-(const Matrix& other) const {
if (m != other.m || n != other.n) {
throw invalid_argument("The dimensions of two matrices are different.");
}
Matrix res(m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[i][j] = data[i][j] - other[i][j];
}
}
return res;
}
// 重载乘法运算符
Matrix operator*(const Matrix& other) const {
if (n != other.m) {
throw invalid_argument("The number of columns of the first matrix is not equal to the number of rows of the second matrix.");
}
Matrix res(m, other.n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < other.n; j++) {
double sum = 0;
for (int k = 0; k < n; k++) {
sum += data[i][k] * other[k][j];
}
res[i][j] = sum;
}
}
return res;
}
// 重载除法运算符
Matrix operator/(double x) const {
Matrix res(m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res[i][j] = data[i][j] / x;
}
}
return res;
}
// 输出矩阵
friend ostream& operator<<(ostream& os, const Matrix& mat) {
for (int i = 0; i < mat.m; i++) {
for (int j = 0; j < mat.n; j++) {
os << mat[i][j] << " ";
}
os << endl;
}
return os;
}
};
// 测试
int main() {
Matrix A(2, 3);
A[0][0] = 1; A[0][1] = 2; A[0][2] = 3;
A[1][0] = 4; A[1][1] = 5; A[1][2] = 6;
cout << "A = " << endl << A << endl;
Matrix B(2, 3);
B[0][0] = 7; B[0][1] = 8; B[0][2] = 9;
B[1][0] = 10; B[1][1] = 11; B[1][2] = 12;
cout << "B = " << endl << B << endl;
Matrix C = A + B;
cout << "C = A + B = " << endl << C << endl;
Matrix D = A - B;
cout << "D = A - B = " << endl << D << endl;
Matrix E(3, 2);
E[0][0] = 1; E[0][1] = 2;
E[1][0] = 3; E[1][1] = 4;
E[2][0] = 5; E[2][1] = 6;
cout << "E = " << endl << E << endl;
Matrix F = A * E;
cout << "F = A * E = " << endl << F << endl;
Matrix G = A / 2;
cout << "G = A / 2 = " << endl << G << endl;
return 0;
}
阅读全文