#include <iostream>
using namespace std;
class A {
int num;
public:
A(int a=0):num(a){}
A operator++(int) {
A a(*this);
this->num++;
return a;
}
A& operator++() {
this->num++;
return *this;
}
void show() {
cout<<num<<endl;
}
};
int main() {
A a(1);
A b=a++;
A c=++a;
a.show();
b.show();
c.show();
return 0;
}
这是一个最常见的“++”运算符重载了
A operator++(int) { //++放在后面的重载eg:b=a++
A a(*this); //下面那个就是b=++a的重载了
this->num++;
return a;
}
在b站的一个up主那里学到了一个新的重载方法:
#include <iostream>
using namespace std;
class A {
int num;
public:
A(int a=0):num(a){}
void show() {
cout<<num<<endl;
}
A operator++(int) { //后置要有无关参数(int)
return A(this->num++);
}
A operator++() { //前置不用
return A(++this->num);
}
};
int main() {
A a(1);
A b=a++;
b.show();
a.show();
A c=++a;
c.show();
a.show();
return 0;
}