(1)重载运算符“<<”和“>>”的算法实现。
#include "pch.h"
#include <iostream>
using namespace std;
class Point
{
public:
Point()
{};
friend istream & operator >> (istream &input, Point &p); //重载运算符">>"
friend ostream & operator << (ostream &output, Point &p); //重载运算符"<<"
private:
int x, y;
};
istream & operator >> (istream & input, Point & p)
{
cout << "请输入x, y的值:" << endl;
cout << "x=";
input >> p.x;
cout << "y=";
input >> p.y;
return input;
}
ostream & operator << (ostream & output, Point & p)
{
output << "输出x, y的值" << endl;
output << "x=" << p.x << " y=" << p.y << endl;
return output;
}
void main()
{
Point P;
cin >> P;
cout << P;
}
(2)编写程序,有两个均为3行3列的矩阵ml和m2,求两个矩阵之和。重载运算符“+”、“>>”和“<<”,使之能用于矩阵相加、输入和输出。
#include "pch.h"
#include <iostream>
using namespace std;
class Ju
{
int a[3][3];
public:
Ju() {};
Ju & operator = (const Ju & t);//重载运算符=
friend istream & operator >>(istream &input, Ju &p);//重载运算符>>
friend ostream & operator << (ostream & output, Ju &p);//重载运算符<<
friend Ju operator +(Ju &m1, Ju &m2);//重载运算符+
};
Ju & Ju::operator=(const Ju & t)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
a[i][j] = t.a[i][j];
}
return *this;
}
istream & operator >>(istream &input, Ju &p)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
input >> p.a[i][j];
}
return input;
}
ostream & operator << (ostream &output, Ju &m3)
{
for (int i = 0; i < 3; i++)
{
int j;
for (j = 0; j < 3; j++)
output << m3.a[i][j] << " ";
if (j = 2)
cout << endl;
}
return output;
}
Ju operator +(Ju &m1, Ju &m2)
{
Ju temp;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
temp.a[i][j] = m1.a[i][j] + m2.a[i][j];
}
return temp;
}
void main()
{
Ju m1, m2, m3;
cout << "请输入第一个矩阵" << endl;
cin >> m1;
cout << "请输入第二个矩阵" << endl;
cin >> m2;
cout << "两个矩阵的和" << endl;
m3 = m1 + m2;
cout << m3;
}