C++ 操作符重载前置和后置

系统中的++运算符放在变量的前面和后面是有区别的,如果我们自己的类想要实现++操作符的前置和后置功能如下。

比如有一个Person类,里面有一个int类型的age属性,当我们Person p;p++;就是对里面的属性age++,并且(p++)返回++之前的对象p。Person p;++p;对里面的属性age++,并且(++p)返回++之后的对象p。

实现代码:

#include <iostream>

class Person
{
private:
    /* data */
public:
    int age;
    Person& operator++();
    Person operator++(int);
};

Person& Person::operator++(){//没有参数表示后置运算符p++
    std::cout<<"前置调用"<<std::endl;
    this->age++;
    return *this;
}

Person Person::operator++(int){//有一个int变量表示前置运算符++p,int变量在代码中不使用,只是为了区分后置和前置。
    std::cout<<"后置调用"<<std::endl;
    Person ret = *this;
    ++*this;
    return ret;
}
 
int main(){
    Person p;
    p.age = 10;
    auto relP = (++p);
    std::cout<<relP.age<<std::endl;
    Person p1;
    p1.age = 10;
    auto relP1 = (p1++);
    std::cout<<relP1.age<<std::endl;
    return 0;
}
原文地址:https://www.cnblogs.com/maycpou/p/14793651.html