题目描述

#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix();
friend Matrix operator*(int k,Matrix &);
friend ostream& operator<<(ostream&,Matrix&);
friend istream& operator>>(istream&,Matrix&);
private:
int mat[2][3];
};
Matrix::Matrix()
{
for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
mat[i][j]=0;
}
ostream& operator<<(ostream &out,Matrix &mat)
{
for (int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
if(j>0) out<<" ";
out<<mat.mat[i][j];
}
out<<endl;
}
return out;
}
/*

*/

int main()
{
Matrix mat1,mat2;
int k;
cin>>k;
cin>>mat1;
mat2=k*mat1;
cout<<mat2<<endl;
return 0;
}

2
1 2 3
4 5 6

2 4 6
8 10 12

代码如下

``````
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix();
friend Matrix operator*(int k,Matrix &);
friend ostream& operator<<(ostream&,Matrix&);
friend istream& operator>>(istream&,Matrix&);
private:
int mat[2][3];
};
Matrix::Matrix()
{
for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
mat[i][j]=0;
}
ostream& operator<<(ostream &out,Matrix &mat)
{
for (int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
if(j>0) out<<" ";
out<<mat.mat[i][j];
}
out<<endl;
}
return out;
}
istream& operator>>(istream& inp,Matrix &b)
{
for (int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
inp>>b.mat[i][j];
}
}
return inp;
}
Matrix operator*(int k,Matrix &c)
{
for (int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
c.mat[i][j]*=k;
}
}
return c;
}
int main()
{
Matrix mat1,mat2;
int k;
cin>>k;
cin>>mat1;
mat2=k*mat1;
cout<<mat2<<endl;
return 0;
}
``````