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;
}
相关推荐
_w_z_j_1 分钟前
C++----变量存储空间
开发语言·c++
龙腾AI白云7 分钟前
大模型-高效优化技术全景解析:微调 量化 剪枝 梯度裁剪与蒸馏 上
算法
花菜会噎住10 分钟前
Vue3 路由配置和使用与讲解(超级详细)
开发语言·javascript·ecmascript·路由·router
细节控菜鸡13 分钟前
【2025最新】ArcGIS for JavaScript 快速实现热力图渲染
开发语言·javascript·arcgis
地平线开发者20 分钟前
新版 perf 文件解读与性能分析
算法·自动驾驶
lingran__23 分钟前
算法沉淀第五天(Registration System 和 Obsession with Robots)
c++·算法
chrispang25 分钟前
浅谈 Tarjan 算法
算法
莱茶荼菜26 分钟前
一个坐标转换
c++·算法
guguhaohao1 小时前
list,咕咕咕!
数据结构·c++·list
PingdiGuo_guo1 小时前
C++构造和折构函数详解,超详细!
开发语言·c++