1. 设计矩阵类Matrix(请参照教材page:281矩阵的设计),实现运算符重载。要求: (1)设有两个矩阵A和B,均为3行3列。重载运算符“+”和“*”,使之分别能用于矩阵相加和相乘,C = A+B, C = A*B(30分)。 (2)矩阵能够使用“<<”运算符输出(15分) class Matrix { public: Matrix(int size=2); //构造函数 Matrix(const Matrix &M); //复制构造函数 ~Matrix(); //析构函数 void setMatrix(const int *value); //矩阵赋初值 Matrix operator + (Matrix &m); //重载 + 运算符 Matrix operator * (Matrix &m); //重载 * 运算符 friend ostream &operator << (ostream &out, const Matrix &m); //重载"<<"运算符 int getSize() const {return size;} //得到矩阵大小 int &element(int i,int j) {return elements[i*size+j];}//获取元素 int element(int i,int j) const {return elements[i*size+j];} private: int size; //矩阵的大小 int *elements; //用于存放数组的首地址 }; int main(void) { int a[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int b[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Matrix m1(3); m1.setMatrix(*a); Matrix m2(3); m2.setMatrix(*b); Matrix m3 = m1+m2; Matrix m4 = m1*m2; cout << "m3 = " << endl << m3 << endl; cout << "m4 = " << endl << m4 << endl; return 0; }
时间: 2024-03-25 21:39:27 浏览: 101
好的,我明白了你的问题。这是一个关于矩阵类Matrix的运算符重载的问题,要求实现矩阵相加和相乘,并且能够使用“<<”运算符输出矩阵。下面是代码实现:
```c++
#include <iostream>
using namespace std;
class Matrix {
public:
Matrix(int size = 2); //构造函数
Matrix(const Matrix &M); //复制构造函数
~Matrix(); //析构函数
void setMatrix(const int *value); //矩阵赋初值
Matrix operator + (Matrix &m); //重载 + 运算符
Matrix operator * (Matrix &m); //重载 * 运算符
friend ostream &operator << (ostream &out, const Matrix &m); //重载"<<"运算符
int getSize() const { return size; } //得到矩阵大小
int &element(int i, int j) { return elements[i*size + j]; }//获取元素
int element(int i, int j) const { return elements[i*size + j]; }
private:
int size; //矩阵的大小
int *elements; //用于存放数组的首地址
};
Matrix::Matrix(int size) {
this->size = size;
elements = new int[size*size];
}
Matrix::Matrix(const Matrix &M) {
size = M.size;
elements = new int[size*size];
for (int i = 0; i < size*size; i++)
elements[i] = M.elements[i];
}
Matrix::~Matrix() {
delete[] elements;
}
void Matrix::setMatrix(const int *value) {
for (int i = 0; i < size*size; i++)
elements[i] = value[i];
}
Matrix Matrix::operator+(Matrix &m) {
Matrix result(size);
for (int i = 0; i < size*size; i++)
result.elements[i] = elements[i] + m.elements[i];
return result;
}
Matrix Matrix::operator*(Matrix &m) {
Matrix result(size);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int sum = 0;
for (int k = 0; k < size; k++)
sum += elements[i*size + k] * m.elements[k*size + j];
result.elements[i*size + j] = sum;
}
}
return result;
}
ostream &operator<<(ostream &out, const Matrix &m) {
for (int i = 0; i < m.size; i++) {
for (int j = 0; j < m.size; j++)
out << m.elements[i*m.size + j] << " ";
out << endl;
}
return out;
}
int main(void) {
int a[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int b[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Matrix m1(3);
m1.setMatrix(*a);
Matrix m2(3);
m2.setMatrix(*b);
Matrix m3 = m1 + m2;
Matrix m4 = m1 * m2;
cout << "m3 = " << endl << m3 << endl;
cout << "m4 = " << endl << m4 << endl;
return 0;
}
```
希望我的回答能够帮到你!
阅读全文