C++实验内容: 假设square_matrix是n阶整型方阵,请实现下列运算: (1)cin>> square_matrix (2)cout<< square_matrix (3)IntMatrix(n)生成一个n阶单位矩阵 (4)square_matrix+IntMatrix(n) (5)square_matrix_A=square_matrix_B
时间: 2023-06-14 22:08:30 浏览: 168
下面是 C++ 实现:
```c++
#include <iostream>
using namespace std;
class IntMatrix {
private:
int **matrix; // 二维动态数组
int n; // 方阵阶数
public:
// 构造函数,创建一个 n 阶方阵,默认为零矩阵
IntMatrix(int n) {
this->n = n;
matrix = new int*[n];
for (int i = 0; i < n; i++) {
matrix[i] = new int[n];
for (int j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}
}
// 拷贝构造函数
IntMatrix(const IntMatrix& other) {
n = other.n;
matrix = new int*[n];
for (int i = 0; i < n; i++) {
matrix[i] = new int[n];
for (int j = 0; j < n; j++) {
matrix[i][j] = other.matrix[i][j];
}
}
}
// 重载输入运算符
friend istream& operator>>(istream& in, IntMatrix& m) {
for (int i = 0; i < m.n; i++) {
for (int j = 0; j < m.n; j++) {
in >> m.matrix[i][j];
}
}
return in;
}
// 重载输出运算符
friend ostream& operator<<(ostream& out, const IntMatrix& m) {
for (int i = 0; i < m.n; i++) {
for (int j = 0; j < m.n; j++) {
out << m.matrix[i][j] << " ";
}
out << endl;
}
return out;
}
// 重载加法运算符
IntMatrix operator+(const IntMatrix& other) const {
IntMatrix m(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
m.matrix[i][j] = matrix[i][j] + other.matrix[i][j];
}
}
return m;
}
// 重载赋值运算符
IntMatrix& operator=(const IntMatrix& other) {
if (this != &other) {
// 先删除原有的矩阵
for (int i = 0; i < n; i++) {
delete[] matrix[i];
}
delete[] matrix;
// 重新分配内存
n = other.n;
matrix = new int*[n];
for (int i = 0; i < n; i++) {
matrix[i] = new int[n];
for (int j = 0; j < n; j++) {
matrix[i][j] = other.matrix[i][j];
}
}
}
return *this;
}
// 析构函数,释放动态内存
~IntMatrix() {
for (int i = 0; i < n; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
};
int main() {
int n;
cin >> n;
// 输入方阵
IntMatrix square_matrix(n);
cin >> square_matrix;
// 输出方阵
cout << square_matrix;
// 生成单位矩阵
IntMatrix unit_matrix(n);
for (int i = 0; i < n; i++) {
unit_matrix.matrix[i][i] = 1;
}
// 方阵加单位矩阵
IntMatrix result = square_matrix + unit_matrix;
cout << result;
// 赋值
IntMatrix square_matrix_A = square_matrix;
cout << square_matrix_A;
return 0;
}
```
阅读全文