一、实验目的及要求
- 了解在集成开发环境下程序的编辑、编译、连接、运行与调试;
二、实验设备与平台
- 实验设备:计算机;
- 平台:Windows 2000操作系统,Visual C++ 6.0或Microsoft Visual Studio 2005/2008/2010/2012/2013。
三、实验内容及步骤
1、重载运算符“<<”和“>>”的算法实现。
#include<iostream>
using namespace std;
class Point
{
int x, y;
public:
friend istream& operator >> (istream& in, Point& p);
friend ostream& operator << (ostream& out, Point& p);
};
istream& operator >> (istream& in, Point& p)
{
cout << "x=";
in >> p.x;
cout << "y=";
in >> p.y;
return in;
}
ostream& operator << (ostream& out, Point& p)
{
out << "x=" << p.x << " y=" << p.y << endl;
return out;
}
int main()
{
Point P;
cout << "请输入x, y的值:" << endl;
cin >> P;
cout << "输出x, y的值" << endl;
cout << P;
}
2、编写程序,有两个均为3行3列的矩阵ml和m2,求两个矩阵之和。重载运算符“+”、“>>”和“<<”,使之能用于矩阵相加、输入和输出。
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix(){}
Matrix(const Matrix&);
friend Matrix operator+( Matrix& a, Matrix& b);
friend ostream& operator<<(ostream& a, const Matrix& b);
friend istream& operator>>(istream& a, Matrix& b);
private:
double a[3][3];
};
Matrix::Matrix(const Matrix& b)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
a[i][j] = b.a[i][j];
}
}
}
Matrix operator+( Matrix& a, Matrix& b)
{
Matrix p;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
p.a[i][j] = a.a[i][j] + b.a[i][j];
}
}
return p;
}
ostream& operator<<(ostream& out,const Matrix& b)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
out << b.a[i][j]<<'\t';
}
cout << '\n';
}
return out;
}
istream& operator>>(istream& in, Matrix& b)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
in >> b.a[i][j];
}
}
return in;
}
int main()
{
Matrix a, b;
cout << "请输入第一个矩阵的元素:\n";
cin >> a;
cout << "请输入第2个矩阵的元素:\n";
cin >> b;
cout << "两个矩阵相加的结果为:\n";
cout << a + b;
}