/* 请在此处分别编写Matrix类、重载operator*函数、printMatrix函数 */ template class Matrix { public: Matrix(int row, int column); Matrix(int row, int column, const T& value); Vector& operator[](int index); Vector operator[](int index) const; int getRows() const; int getColumns() const; private: Vector<Vector*> rows; // 存放矩阵元素 }; template Matrix::Matrix(int row, int column) : rows(row) { for (int i = 0; i < row; i++) { rows[i] = new Vector(column); } } template Matrix::Matrix(int row, int column, const T& value) :rows(row) { for (int i = 0; i < row; i++) { rows[i] = new Vector(column, value); } } template Vector& Matrix::operator[](int index) { return *rows[index]; } template Vector Matrix::operator[](int index) const { return *rows[index]; } template int Matrix::getRows() const{ return rows.getSize(); } template int Matrix::getColumns() const{ return rows[0]->getSize(); } template Matrix operator*(const Matrix& lhs, const Matrix& rhs) { Matrix res(lhs.getRows(), rhs.getColumns(), 0); for (int i = 0; i < lhs.getRows(); i++) { for (int j = 0; j < rhs.getColumns(); j++) { for (int k = 0; k < lhs.getColumns(); k++) { res[i][j] += lhs[i][k] * rhs[k][j]; } } } return res; } template void printMatrix(const Matrix& m) { for (int i = 0; i < m.getRows(); i++) { for (int j = 0; j < m.getColumns(); j++) { cout << setw(4) << setfill(' ') << m[i][j]; } } }修复代码
时间: 2023-12-03 09:44:12 浏览: 61
C/C++面试题:编写类String的构造、析构和赋值函数
修复后的代码:
```cpp
#include <iostream>
#include <iomanip>
#include "Vector.h"
using namespace std;
template<class T>
class Matrix {
public:
Matrix(int row, int column);
Matrix(int row, int column, const T& value);
Vector<T>& operator[](int index);
Vector<T> operator[](int index) const;
int getRows() const;
int getColumns() const;
private:
Vector<Vector<T>*> rows; // 存放矩阵元素
};
template<class T>
Matrix<T>::Matrix(int row, int column) : rows(row) {
for (int i = 0; i < row; i++) {
rows[i] = new Vector<T>(column);
}
}
template<class T>
Matrix<T>::Matrix(int row, int column, const T& value) :rows(row) {
for (int i = 0; i < row; i++) {
rows[i] = new Vector<T>(column, value);
}
}
template<class T>
Vector<T>& Matrix<T>::operator[](int index) {
return *rows[index];
}
template<class T>
Vector<T> Matrix<T>::operator[](int index) const {
return *rows[index];
}
template<class T>
int Matrix<T>::getRows() const {
return rows.getSize();
}
template<class T>
int Matrix<T>::getColumns() const {
return rows[0]->getSize();
}
template<class T>
Matrix<T> operator*(const Matrix<T>& lhs, const Matrix<T>& rhs) {
Matrix<T> res(lhs.getRows(), rhs.getColumns(), 0);
for (int i = 0; i < lhs.getRows(); i++) {
for (int j = 0; j < rhs.getColumns(); j++) {
for (int k = 0; k < lhs.getColumns(); k++) {
res[i][j] += lhs[i][k] * rhs[k][j];
}
}
}
return res;
}
template<class T>
void printMatrix(const Matrix<T>& m) {
for (int i = 0; i < m.getRows(); i++) {
for (int j = 0; j < m.getColumns(); j++) {
cout << setw(4) << setfill(' ') << m[i][j];
}
cout << endl;
}
}
```
阅读全文