使用类与对象、运算符重载等知识点,实现矩阵类类型,并扩展适合于矩阵类型的+、-、*、/等运算功能。 本题中的矩阵是指一个按照长方阵列排列的实数集合,具有多行多列。由 m × n 个数aij排成的m行n列的数表称为m行n列的矩阵,简称m × n矩阵。记作
时间: 2024-04-02 22:31:56 浏览: 12
class Matrix {
private:
int rows;
int cols;
double **data;
public:
// 构造函数
Matrix(int rows, int cols) {
this->rows = rows;
this->cols = cols;
data = new double*[rows];
for(int i = 0; i < rows; i++) {
data[i] = new double[cols];
for(int j = 0; j < cols; j++) {
data[i][j] = 0;
}
}
}
// 拷贝构造函数
Matrix(const Matrix& other) {
rows = other.rows;
cols = other.cols;
data = new double*[rows];
for(int i = 0; i < rows; i++) {
data[i] = new double[cols];
for(int j = 0; j < cols; j++) {
data[i][j] = other.data[i][j];
}
}
}
// 析构函数
~Matrix() {
for(int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
// 运算符重载
Matrix operator+(const Matrix& other) const {
if(rows != other.rows || cols != other.cols) {
throw "矩阵大小不一致";
}
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 "矩阵大小不一致";
}
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(cols != other.rows) {
throw "矩阵大小不匹配";
}
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.data[i][j] += data[i][k] * other.data[k][j];
}
}
}
return result;
}
Matrix operator/(const double& num) const {
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] / num;
}
}
return result;
}
// 打印矩阵
void print() const {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << data[i][j] << " ";
}
cout << endl;
}
}
};
// 示例
int main() {
Matrix a(2, 3);
a.print();
cout << endl;
Matrix b(2, 3);
b.print();
cout << endl;
Matrix c = a + b;
c.print();
cout << endl;
Matrix d = a - b;
d.print();
cout << endl;
Matrix e(3, 2);
e.print();
cout << endl;
Matrix f = a * e;
f.print();
cout << endl;
Matrix g = a / 2;
g.print();
cout << endl;
return 0;
}