64,649
社区成员
发帖
与我相关
我的任务
分享
template < class T > class Matrix
{
private:
int Row;
int Column;
T **Data;
public:
......
Matrix & operator* (const Matrix & M);
Matrix & operator* (const T M);
};
...
template < class T > Matrix < T > &Matrix < T >::operator* (const Matrix & M)
{
if (Column != M.Row)
{
exit (EXIT_FAILURE);
}
Matrix < T > Result (Row, M.Column);
for (int i = 0; i < Row; ++i)
{
for (int j = 0; j < M.Column; ++j)
{
for (int k = 0; k < Column; ++k)
{
Result.Data[i][j] += Data[i][k] * M.Data[k][j];
}
}
}
if (Row != Column)
{
for (int i = 0; i < Row; ++i)
{
delete[]Data[i];
}
delete[]Data;
}
Column = Result.Column;
Data = new T *[Row];
for (int i = 0; i < Row; ++i)
{
Data[i] = new T[Column];
for (int j = 0; j < Column; ++j)
{
Data[i][j] = Result[i][j];
}
}
return *this;
}
template < class T > Matrix < T > &Matrix < T >::operator* (const T M)
{
for (int i = 0; i < Row; ++i)
{
for (int j = 0; j < Column; ++j)
{
Data[i][j] *= M;
}
}
return *this;
}
4 1 2 5
5 2 1 3
2 4 5 7
5 4 3 2 1
2 3 4 5 6
1 2 4 5 7
1 5 5 5 5
29 48 49 48 49
33 43 42 40 39
30 65 77 84 96
请按任意键继续. . .
#include <iostream>
#include <iomanip>
using namespace std;
int a[3][4]=
{
{4,1,2,5},
{5,2,1,3},
{2,4,5,7}};
int b[4][5]={{5,4,3,2,1},
{2,3,4,5,6},
{1,2,4,5,7},
{1,5,5,5,5}};
int c[3][5];
void main()
{ int c[3][5]={0}; //没有初始化;
int i,j;
for( i=0;i <3;i++)
{ for( j=0;j <4;j++)
cout <<setw(3) <<a[i][j];
cout <<endl;
}
cout <<endl <<endl;
for( i=0;i <4;i++)
{ for( j=0;j <5;j++)
cout <<setw(3) <<b[i][j];
cout <<endl;
}
for( i=0;i <3;i++)
for( j=0;j <5;j++)
for(int k=0;k <4;k++)
c[i][j]+=a[i][k]*b[k][j];
for( i=0;i <3;i++)
{for(int j=0;j <5;j++)
cout <<setw(5) <<c[i][j];
cout <<endl;
}
}