题目描述
声明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 real, imag;
public:
Point(int r = 0, int i = 0)
{
real = r;
imag = i;
}
friend ostream& operator<<(ostream&, Point &);
friend istream& operator>>(istream&, Point &);
friend Point operator--(Point&, int);
friend Point operator-(Point, Point);
Point& operator++();
Point& operator+(Point);
};
ostream& operator<<(ostream& output, Point &obj)
{
output << "(" << obj.real << "," << obj.imag << ")";
return output;
}
istream & operator>>(istream& input, Point &obj)
{
input >> obj.real;
input >> obj.imag;
return input;
}
Point operator-(Point a, Point b)
{
Point temp(0, 0);
temp.real = a.real - b.real;
temp.imag = a.imag - b.imag;
return temp;
}
Point &Point ::operator++()//单目运算符成员函数的返回值是this指针比如是return (*this)
{
real++;
imag++;
return (*this);
}
Point &Point ::operator+(Point a)
{
static Point temp(0, 0);
temp.real = real + a.real;
temp.imag = imag + a.imag;
return temp;
}
Point operator--(Point &op, int)//后置
{
Point temp;
temp = op;
op.imag--;
op.real--;
return temp;
}
int main()
{
Point p1, p2, p;
cin >> p1 >> p2;
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;
}