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;
}
相关推荐
web安全工具库3 分钟前
Makefile 模式规则精讲:从 %.o: %.c 到静态模式规则的终极自动化
linux·运维·c语言·开发语言·数据库·自动化
從南走到北6 分钟前
JAVA代泊车接机送机服务代客泊车系统源码支持小程序+APP+H5
java·开发语言·微信小程序·小程序
im_AMBER1 小时前
数据结构 06 线性结构
数据结构·学习·算法
earthzhang20213 小时前
【1028】字符菱形
c语言·开发语言·数据结构·c++·算法·青少年编程
papership3 小时前
【入门级-算法-3、基础算法:二分法】
数据结构·算法
通信小呆呆3 小时前
收发分离多基地雷达椭圆联合定位:原理、算法与误差分析
算法·目标检测·信息与通信·信号处理
earthzhang20215 小时前
第3讲:Go垃圾回收机制与性能优化
开发语言·jvm·数据结构·后端·性能优化·golang
AA陈超5 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-08 UI 部件数据表
c++·游戏·ue5·游戏引擎·虚幻
纵有疾風起6 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
Full Stack Developme6 小时前
java.text 包详解
java·开发语言·python