C++之多态

任务1:定义Point类,有坐标xy两个成员变量;对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++。

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值