C++ 面向对象编程:递增重载

这里有两个,分别是前置++,和后置++,具体重载可见下面代码:

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;
}
相关推荐
文弱书生6563 分钟前
5.后台运行设置和包设计与实现
服务器·开发语言·c#
编码浪子7 分钟前
趣味学RUST基础篇(异步补充)
开发语言·后端·rust
宁静致远202111 分钟前
【C++设计模式】第五篇:装饰器模式
c++·设计模式·装饰器模式
songroom13 分钟前
Rust : 关于Deref
开发语言·后端·rust
qq_4017004116 分钟前
QT子线程与GUI线程安全交互
开发语言·qt
高-老师20 分钟前
R语言生物群落(生态)数据统计分析与绘图实践技术应用
开发语言·r语言·生物群落
Joy-鬼魅24 分钟前
怎么生成qt的pro文件
开发语言·qt
青草地溪水旁25 分钟前
Linux 高性能 I/O 事件通知机制的核心系统调用—— `epoll_ctl`
linux·c语言·c++
孙同学_43 分钟前
【C++】AVL树
c++·redis
行走的bug...1 小时前
用图论来解决问题
算法·图论