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; }
相关文章推荐
- [YTU]_2442( C++习题 矩阵求和--重载运算符)
- 第十五周oj刷题——Problem M: C++习题 矩阵求和--重载运算符
- YTU 2442: C++习题 矩阵求和--重载运算符
- C++习题 矩阵求和--重载运算符
- 第十五周oj刷题——Problem M: C++习题 矩阵求和--重载运算符
- OJ-矩阵求和--重载运算符
- 矩阵求和--重载运算符
- 16 oj 矩阵求和 重载运算符
- 矩阵求和--重载运算符
- YTU 2443: C++习题 复数类--重载运算符3+
- YTU-OJ-矩阵求和--重载运算符
- C++习题 复数类--重载运算符2+
- c++实验6-项目3:矩阵求和
- C++习题 复数类--重载运算符+,-,*,/
- YTU 2440: C++习题 复数类--重载运算符+,-,*,/
- YTU 2441: C++习题 复数类--重载运算符2+
- 第十五周oj刷题——Problem L: C++习题 复数类--重载运算符2+
- 矩阵求和--重载运算符
- 第十五周oj刷题——Problem K: C++习题 复数类--重载运算符+,-,*,/
- C++习题 复数类--重载运算符2+