声明Point类,有坐标x,y,为整型的私有数据成员。
声明成员函数:
Point& operator++();
Point& operator+(Point);
Point(int x = 0,int y =0);
声明友元函数:
friend Point operator--(Point&,int);
friend Point operator-(Point,Point);
friend ostream& operator<<(ostream &,Point p);
注意:若一个函数返回的是对象引用,则不返回auto型对象,需要静态存储的对象, 如static类型的对象
主函数中定义Point类的三个对象:p1、p2、p,p1、p2的初始值由键盘输入,p使用默认值。依次实现运算:p=++p1; p=p2--; p=p1+p2; p=p1-p2;后将结果输出。注意结果输出要求使用类似于“cout<<p1;”的形式。
10 9
4 5
p=++p1后,p的坐标为:(11,10),p1坐标为:(11,10)
p=p2--后,p的坐标为:(4,5),p2坐标为:(3,4)
p=p1+p2后,p的坐标为:(14,14)
p=p1-p2后,p的坐标为:(8,6)
代码如下:
#include<iostream>
using namespace std;
class Point {
private:
int x,y;
public:
//成员运算符重载
Point& operator++();
Point& operator+(Point);
Point(int x = 0, int y = 0) :x(x), y(y){}
//友元运算符重载
friend Point operator--(Point&, int);
friend Point operator-(Point, Point);
friend ostream& operator<<(ostream&os, Point p)//输出整个坐标
{
cout << "(" << p.x <<","<< p.y << ")" << endl;
return os;
}
};
Point &Point ::operator+(Point a) {
Point temp;
temp.x = x + a.x;
temp.y = y + a.y;
return temp;
}
Point &Point ::operator++() //先自增则p=p1,都输出p1坐标即可
{
++x;
++y;
return *this;
}
Point operator--(Point&op, int) //要输出两个不同坐标!!!
{
Point temp = op; //区分p和p2坐标
--op.x;
--op.y;
return temp;
}
Point operator-(Point p1, Point p2)
{
Point temp;
temp.x = p1.x - p2.x;
temp.y = p1.y - p2.y;
return temp;
}
int main()
{
int x1, x2, y1, y2;
cin >> x1 >> y1 >> x2 >> y2;
Point p1(x1, y1), p2(x2, y2);
Point p;
p = ++p1;
cout << "p=++p1后,p的坐标为:" << p << ",p1坐标为:" << p1 << endl;
p = p2--;
cout << "p=p2--后,p的坐标为:" << p << ",p2坐标为:" << p2 << endl;
p = p1 + p2;
cout << "p=p1+p2后,p的坐标为:" << p << endl;
p = p1 - p2;
cout << "p=p1-p2后,p的坐标为:" << p << endl;
return 0;
}