这里有两个,分别是前置++,和后置++,具体重载可见下面代码:
cpp
#include<iostream>
using namespace std;
class test {
friend ostream& operator<<(ostream& msg3, test msg4);
public:
test():msg1(0),msg2(0){}
test(int msg1, int msg2) {
this->msg1 = msg1;
this->msg2 = msg2;
}
test& operator++() { // 前置++重载
this->msg1 += 1;
return *this;
}
test operator++(int) { // 后置++重载
test t = *this;
this->msg1 += 1;
return t;
}
private:
int msg1;
int msg2;
};
ostream& operator<<(ostream& msg3, test msg4) {
msg3 << msg4.msg1 << " " << msg4.msg2 ;
return msg3;
}
int main() {
test t(10, 10);
cout << ++t << endl;
cout << t << endl;
cout << t++ << endl;
cout << t << endl;
return 0;
}
但是上面的写法有点繁琐,每一次调用重载的++,都需要进行拷贝构造,下面这个是加了引用的代码:
cpp
#include<iostream>
using namespace std;
class test {
friend ostream& operator<<(ostream& msg3, const test &msg4);
public:
test():msg1(0),msg2(0){}
test(int msg1, int msg2) {
this->msg1 = msg1;
this->msg2 = msg2;
}
test& operator++() { // 前置++重载
this->msg1 += 1;
return *this;
}
test operator++(int) { // 后置++重载
test t = *this;
this->msg1 += 1;
return t;
}
private:
int msg1;
int msg2;
};
ostream& operator<<(ostream& msg3, const test &msg4) {
msg3 << msg4.msg1 << " " << msg4.msg2 ;
return msg3;
}
int main() {
test t(10, 10);
cout << ++t << endl;
cout << t << endl;
cout << t++ << endl;
cout << t << endl;
return 0;
}