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;
}
相关推荐
秦苒&8 分钟前
【C语言指针一】从入门到通透:核心知识点全梳理(内存、变量、运算、const修饰)
c语言·开发语言·c++
星释9 分钟前
Rust 练习册 111:构建锦标赛积分榜系统
开发语言·后端·rust
蓑衣夜行11 分钟前
QtWebEngine 自动重启方案
开发语言·c++·qt·web·qwebengine
爱喝热水的呀哈喽13 分钟前
chns方程 推导简单的能量耗散律,分部积分向量形式,sav初简介
算法
Source.Liu14 分钟前
【LibreCAD】点实体源码解析
c++·qt·cad
lsx20240615 分钟前
XQuery 实例详解
开发语言
代码游侠16 分钟前
应用——统计文件字符数、单词数、行数
服务器·笔记·算法
hefaxiang16 分钟前
猜数字小游戏--用分支和循环实现
c语言·开发语言
小清兔19 分钟前
一个unity中URP的环境下旋转天空盒的脚本(RotationSky)
开发语言·数据库·学习·程序人生·unity·c#·游戏引擎
岁岁的O泡奶21 分钟前
NSSCTF_crypto_[MTCTF 2021 final]ezRSA
经验分享·python·算法·密码学·crypto