任务1:定义Point类,有坐标x,y两个成员变量;对Point类重载+、-、++(前置)、++(后置)四种运算符,实现对坐标值的运行与改变。
要求:
(1) Point类的x,y定义为私有成员;
(2)需包含构造函数、析构函数、和能获取get和设置set数据成员的函数
#include <iostream>
using namespace std;
class coordinate { //坐标类定义
public:
coordinate(int x,int y):x(x),y(y){}//有参数的构造函数
coordinate(){}//无参数的构造函数
~coordinate(){}//析构函数
coordinate operator + (const coordinate &a1) const;//+运算符重载函数声明
coordinate operator - (const coordinate &a1) const;//-运算符重载函数声明
coordinate& operator++();//++前置函数声明
coordinate operator++(int);//++后置函数声明
void get(){cout<<"x="<<x<<","<<"y="<<y<<endl;}
void set(int a,int b){x=a;y=b;}
private:
int x,y;
};
coordinate & coordinate::operator++()//++前置函数体类外实现
{
x++;
y++;
return* this;//this指针指向当前对象(自增后)
}
coordinate coordinate::operator++(int)
{
coordinate old=*this;//当前对象的值赋给old
++(*this);//自增
return old;//this指针指向old,正对应了++后置,先使用现在的值,后自增的特点
}
coordinate coordinate::operator+(const coordinate &a1) const//+运算符重载
{
return coordinate(x+a1.x,y+a1.y);
}
coordinate coordinate::operator-(const coordinate &a1) const//-运算符重载
{
return coordinate(x-a1.x,y-a1.y);
}
int main()
{
coordinate c1(1,2),c2(2,3),c3;
c3=c1-c2;
c3.get();
(++c3).get();
(c3++).get();
(++c3).get();
c3=c1+c2;
c3.get();
c3.set(6,5);
c3.get();
return 0;
}
首先给出两点坐标,分别是(1,2)和(2,3);然后进行相减,得到(-1,-1),也就是第一行。然后进行前置自增运算,得到(0,0),接着进行后置自增运算,得到(0,0),先显示原来的值然后再自增。接着将c1和c2的相加,得到(3,5),通过set函数设置点的坐标为(6,5)并显示。
错误之处,望大家指出。欢迎一起交流、学习C++。