class Person {
public:
Person(int age);
public:
Person();
Person& operator++();
//类内成员函数重载前置“++”,全局函数定义Person& operator++(Person& p);
const Person operator++(int);
//类内成员函数重载后置“++”,全局函数定义const Person& operator++(Person& p,int);
int age;
};
Person::Person(int age) {
this->age = age;
}
Person::Person() {
this->age = 18;//默认18
}
ostream& operator<<(ostream& cout, Person p) {//p使用&引用后置++会报错“?”
cout << p.age;
return cout;
}
//调用时this->operator++可简化为++*this,可以 ++(++*this)
Person& Person::operator++() {
this->age = this->age + 1;
return *this;
}
//调用时this->operator++(int)可简化为*this++;不可以(*this++)++
const Person Person::operator++(int) {
Person p(*this);
this->age = this->age + 1;
return p;
}
void test() {
int a = 12;
Person person(18);
cout << ++(++person) << endl;
cout << person << endl;
cout << person++ << endl;
cout << person++ << endl;
cout << person;
}
int main() {
test();
}