设计一个矩阵类,当创建矩阵类的对象时,根据提供的行数和列数信息,内部可以通过动态内存分配的机制创建一个任意大小的二维数组用来存储矩阵的数据。相应的,对象析构时应该释放动态分配的数组。对Matrix类重载以下运算符:
(1)将下标运算符[]重载为矩阵类的成员函数,实现用对象名加两个下标的形式能够直接访问二维数组元素的效果;
(2)重载“<<”运算符,实现矩阵的输出功能;
(3)重载“+”运算符(重载为非成员的形式),实现矩阵加法;
(4)重载“*”运算符(重载为非成员的形式),实现矩阵乘法;
main函数已经写好,请根据main函数的内容完成该类的设计。
int main(){
int a,b;
cin>>a>>b;
Matrix m1(a,b),m2(a,b),m3(b,a);
int i,j;
for(i=0;i for(j=0;j cin>>m1[i][j]; for(i=0;i for(j=0;j cin>>m2[i][j]; for(i=0;i for(j=0;j cin>>m3[i][j]; cout<<"Matrix M1:"< cout< cout<<"Matrix M2:"< cout< cout<<"Matrix M3:"< cout< cout<<"Result of Matrix Addition:"< cout< cout<<"Result of Matrix Multiplication:"< cout< return 0; } 输入描述 1、第一行输入两个整数a和b 2、接下来输入第一个矩阵:a行b列 3、接下来输入第二个矩阵:a行b列 4、接下来输入第三个矩阵:b行a列 输出描述 依次分别输出三个矩阵的数据 然后输出第一个矩阵和第二个矩阵相加的结果 最后输出第一个矩阵和第三个矩阵相乘的结果 提示 你需要提交除main函数之外的其他代码 注意动态内存分配可能需要解决深复制问题 样例输入 2 3 样例输出 Matrix M1: #include class Matrix public: int getColumns() Matrix(int Rows, int Columns) int *&operator[](int &index) friend ostream &operator<<(ostream &out, Matrix &m) friend Matrix &operator+(Matrix &c1, Matrix &c2) Matrix *m = new Matrix(c1.getRows(), c2.getColumns()); return *m; Matrix &operator*(Matrix &x) //矩阵乘法运算符重载 欢迎分享,转载请注明来源:内存溢出
1 2 3
4 5 6
1 2 3
4 5 6
1 2
3 4
5 6
1 2 3
4 5 6
Matrix M2:
1 2 3
4 5 6
Matrix M3:
1 2
3 4
5 6
Result of Matrix Addition:
2 4 6
8 10 12
Result of Matrix Multiplication:
22 28
49 64
using namespace std;
{
private:
int Rows;
int Columns;
int **arr;
int getRows()
{
return Rows;
}
{
return Columns;
}
{
this->Rows = Rows;
this->Columns = Columns;
arr = new int *;
for (int i = 0; i < Rows; i++)
{
arr[i] = new int[Columns];
}
}
{
return this->arr[index];
}
{
for (int i = 0; i < m.getRows(); i++)
{
for (int j = 0; j < m.getColumns(); j++)
out << m.arr[i][j] << " ";
out << endl;
}
return out;
}
{
for (int i = 0; i < c1.getRows(); i++)
for (int j = 0; j < c1.getColumns(); j++)
{
m->arr[i][j] = c1.arr[i][j] + c2.arr[i][j];
}
}
{
if (this->getColumns() == x.getRows()) //两矩阵相乘必须满足的条件
{
Matrix y(this->getRows(), x.getColumns()); //声明一个暂存数据的矩阵
for (int i0 = 0; i0 < this->getRows(); i0++) //将两矩阵相乘的新矩阵数据导入
{
for (int j0 = 0; j0 < x.getColumns(); j0++)
{
float sum = 0;
int i = 0;
for (int j = 0; j < this->getColumns(); j++, i++)
{
sum = sum + arr[i0][j] * x.arr[i][j0]; //矩阵相乘公式
}
y.arr[i0][j0] = sum;
}
}
x = Matrix(y);
return x;
}
else
{
cout << "error" << endl;
return x;
}
}
};
评论列表(0条)