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;
}
相关推荐
春蕾夏荷_72829772515 小时前
Sockets-2.3.9.9 UDP使用实例
c++·udp
AC赳赳老秦15 小时前
政务数据处理:DeepSeek 适配国产化环境的统计分析与报告生成
开发语言·hadoop·spring boot·postgresql·测试用例·政务·deepseek
xlxxy_15 小时前
abap 批量创建供应商
运维·开发语言·sap·abap·pp·mm
GetcharZp16 小时前
拒绝硬编码!C++ 配置文件管理神器 yaml-cpp 实战指南
c++
独自破碎E16 小时前
Java是怎么实现跨平台的?
java·开发语言
ullio16 小时前
div1+2. 2178F - Conquer or of Forest
算法
墨有66616 小时前
C++ string 部分功能详解:迭代器、初始化与常用函数
开发语言·c++
Leweslyh16 小时前
制导算法开发实践指南:从入门到精通
算法·开发·武器·制导律设计
chushiyunen16 小时前
快慢双指针算法笔记
数据结构·笔记·算法
Evand J16 小时前
【MATLAB例程】三维环境下,EKF融合INS与DVL的核心程序,用于惯导和速度传感器的数据融合滤波。附下载链接
开发语言·matlab