问题描述:
题目要求:定义Point类,有坐标x,y两个成员变量;对Point类重载“++”(自增)、“--”(自减)运算符,实现对坐标值的改变。
我编完后能运行,但自增自减的初始值似乎只能是(0,0),是因为前后置出问题了吗?
请大家帮忙,谢谢
我的程序:
class CPoint
{
public:
CPoint()
{
x=0;y=0;
}
CPoint(int a, int b)
{
x=a;y=b;
}
void show()
{
cout<<"the point is"<<x<<","<<y<<endl;
}
CPoint operator ++(int);
CPoint operator --(int);
private:
int x,y;
};
CPoint CPoint::operator ++(int)
{
CPoint one;
one.x++;
one.y++;
return one;
}
CPoint CPoint::operator --(int)
{
CPoint one;
one.x--;
one.y--;
return one;
}
void main()
{
CPoint a(2,2),b,c;
a.show();
a++.show();
a--.show();
}
运行结果:
the point is2,2
the point is1,1
the point is-1,-1
Press any key to continue
我没有使用过this函数,fixend朋友的建议照做后无法通过编译,可以再详细点吗?
谢谢了
问题解答:
this是个指针,指向对象本身,所有可以实例化的类都有这个。
我写错了,应该是用->来访问的。
this->x++;
自己试着写一下,不明白再问。
学习