您的位置:首页 > 编程语言 > C语言/C++

C++习题 矩阵求和--重载运算符

2014-07-09 16:16 387 查看

Problem U: C++习题 矩阵求和--重载运算符

Time Limit: 1 Sec  Memory Limit:
128 MB
Submit: 839  Solved: 309

[Submit][Status][Web
Board]

Description

有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加(如c=a+b)。

重载流插入运算符“<<”和流提取运算符“>>”,使之能用于该矩阵的输入和输出。

Input

两个2行3列矩阵

Output

矩阵之和

Sample Input

1 2 3
4 5 6

7 8 9
1 2 3


Sample Output

8 10 12
5 7 9


HINT

前置代码及类型定义已给定如下,提交时不需要包含,会自动添加到程序前部

/* C++代码 */

#include <iostream>

using namespace std;

class Matrix

{

public:

    Matrix();

    friend Matrix operator+(Matrix &,Matrix &);

    friend ostream& operator<<(ostream&,Matrix&);

    friend istream& operator>>(istream&,Matrix&);

private:

    int mat[2][3];

};

主函数已给定如下,提交时不需要包含,会自动添加到程序尾部

/* C++代码 */

int main()

{

    Matrix a,b,c;

    cin>>a;

    cin>>b;

    c=a+b;

    cout<<c<<endl;

    return 0;

}

#include <iostream>
using namespace std;

class Matrix

{

public:

Matrix();

friend Matrix operator+(Matrix &,Matrix &);

friend ostream& operator<<(ostream&,Matrix&);

friend istream& operator>>(istream&,Matrix&);

private:

int mat[2][3];

};

Matrix::Matrix()
{
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
mat[y][x]=0;
}
}
}
Matrix operator+(Matrix &m1,Matrix &m2)
{
Matrix m;
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
m.mat[y][x]=m1.mat[y][x]+m2.mat[y][x];
}
}
return m;
}
istream& operator>>(istream&input,Matrix&m)
{
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
input>>m.mat[y][x];
}
}
return input;
}

ostream& operator<<(ostream&output,Matrix&m)
{
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
if(x<2)
output<<m.mat[y][x]<<' ';
else
output<<m.mat[y][x];
}
if(y<1)
{
cout<<endl;
}
}
return output;
}

int main()

{
Matrix a,b,c;

cin>>a;

cin>>b;

c=a+b;

cout<<c<<endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class 对象 operator