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;
}
相关推荐
xiaobin889991 分钟前
matlab官方免费下载安装超详细教程2025最新matlab安装教程(MATLAB R2024b)
java·开发语言·其他·matlab
Takoony4 分钟前
正则表达式r前缀使用指南
开发语言·正则表达式·r语言
搏博10 分钟前
WPS中代码段的识别方法及JS宏实现
开发语言·javascript·wps
hjjdebug12 分钟前
c/c++数据类型转换.
c语言·c++·数据类型变换
vortex515 分钟前
Bash fork 炸弹 —— :(){ :|:& };:
运维·服务器·开发语言·网络安全·bash
熬夜学编程的小王16 分钟前
【C++进阶篇】C++容器完全指南:掌握set和map的使用,提升编码效率
c++·set·map
花火QWQ17 分钟前
图论模板(部分)
c语言·数据结构·c++·算法·图论
Pacify_The_North32 分钟前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
superior tigre40 分钟前
C++学习:六个月从基础到就业——C++20:协程(Coroutines)
c++·学习·c++20
superior tigre1 小时前
C++学习:六个月从基础到就业——C++20:概念(Concepts)
c++·学习·c++20