注册 登录
编程论坛 C++教室

++和--运算符重载的指针问题

渐渐鱼 发布于 2018-05-15 21:31, 1597 次点击
程序代码:
#include<iostream>
using namespace std;
class Point
{
    public:
    Point(){}
    Point(int vx,int vy)
    {
        x=vx;
        y=vy;
    }
    void display()
    {
        cout<<"<"<<x<<","<<y<<">"<<endl;   
    }
    Point &  operator++();    //前置自增
    Point operator++(int);  //后置自增
    friend Point & operator--(Point &p);  //前置自减
    friend Point operator--(Point &p,int); //后置自减
    private:
        int x,y;

 };

 Point &Point::operator++()   //前置自增
{
     if(x<640)
     x++;
     if(y<480)
     y++;
     return *this;

 }

 Point Point::operator++(int) //后置自增
{
     Point temp(*this);
     if(x<640)
     x++;
     if(y<480)
     y++;
     return temp;

 }

 Point &operator--(Point &p)   //前置自减
{
     if(p.x>0)
     p.x--;
     if(p.y>0)
     p.y--;
     return p;

 }

 Point operator--(Point &p,int)    //后置自减
{
     Point temp(p);
     if(p.x>0)
     p.x--;
     if(p.y>0)
     p.y--;
     return temp;

 }

 int main()

 {
     Point p1(200,200),p2(300,300),p3(400,400),p4(50,50);
     
    cout<<"p1=";  //测试前置自增
    p1.display();
    ++p1;
    cout<<"++p1=";
    p1.display();
   
    cout<<"p2=";    //测试前置自减
    p2.display();
    ++p2;
    cout<<"++p2=";
    p2.display();
   
    cout<<"p3=";   //测试后置自增
    p3.display();
    p3++;
    cout<<"p3++=";
    p3.display();
   
    cout<<"p4=";    //测试后置自减
    p4.display();
    p4--;
    cout<<"p4--";
    p4.display();
   
    return 0;

 }

 



代码里运算符重载里的return *this指针不是特别理解,求大神解!!!!还有那个Point temp(*this)是个什么操作。。。
3 回复
#2
lin51616782018-05-15 22:33
this 是一个Point指针
*this 就是一个Point对象了
灵活一点 难道一定得写成
Point* p = this;
return *p;
才能看懂吗

Point temp(*this);
拷贝构造函数 了解一下
#3
Jonny02012018-05-18 13:54
问题主要出在你不理解 this
this 是一个指针, 类里面拥有的, this 在运行的时候指向类自己
比如有一个 Point x;
当执行 Point 类里面其中一个成员函数的时候, 想要访问类自己里面的成员, 可以通过 this->成员名称 去访问
简单的说, 你可以把 this 理解成自己的
比如你的
Point(int vx,int vy)
    {
        x=vx;
        y=vy;
    }
其实可以改成
Point(int x,int y)
    {
        this->x=x;
        this->y=y;
    }
而不会产生歧义
因为 this->x 是自己的 x, 而后面的 x 是外部传入进来的

而你说的 *this 就是指针解引用之后的结果

比如 int *p
对 p 解引用 *p 得到的不是地址, 就是地址里面指针的值, 而且这是一个引用, *p 变了指针对应的值也会改变

return *this 就是把自己作为函数的返回值传出去
#4
Jonny02012018-05-18 13:54
建议重新学习引用和指针
1