#include<iostream>
using namespace std;
class M
{
private:
int Q[2][3];
public:
friend M operator + (M& x, M& y);
friend ostream& operator<<(ostream& output, M& a);
friend istream& operator>>(istream& input, M& a);
};
M operator + (M& x, M& y)
{
M c;
int i, j;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
c.Q[i][j] = x.Q[i][j] + y.Q[i][j];
}
}
return c;
}
ostream& operator<<(ostream& output, M& a)
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
output << a.Q[i][j] << " ";
}
output << endl;
}
return output;
}
istream& operator>>(istream& input, M& a)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
input >> a.Q[i][j];
return input;
}
int main()
{
M c1, c2, c3;
cin >> c1;
cin >> c2;
c3 = c1 + c2;
cout << c3 << endl;
return 0;
}
这篇博客展示了如何使用C++的面向对象编程来设计一个M类,并重载运算符+和<<,以实现两个2行3列矩阵的相加和打印。通过友元函数实现矩阵元素的输入、输出和相加操作,最后在main函数中进行实例化并展示结果。

被折叠的 条评论
为什么被折叠?



