0
点赞
收藏
分享

微信扫一扫

成员函数重载operator++

知年_7740 2022-02-24 阅读 24
c++
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();
}
举报

相关推荐

0 条评论