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;
}
相关推荐
oioihoii5 分钟前
C++11 forward_list 从基础到精通:原理、实践与性能优化
c++·性能优化·list
满分观察网友z9 分钟前
开发者的“右”眼:一个树问题如何拯救我的UI设计(199. 二叉树的右视图)
算法
m0_6873998413 分钟前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
爱上语文23 分钟前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端
A~taoker29 分钟前
taoker的项目维护(ng服务器)
java·开发语言
萧曵 丶32 分钟前
Rust 中的返回类型
开发语言·后端·rust
hi星尘1 小时前
深度解析:Java内部类与外部类的交互机制
java·开发语言·交互
看到我,请让我去学习1 小时前
Qt编程-qml操作(js,c++,canvas)
开发语言·qt
橘子编程1 小时前
Python-Word文档、PPT、PDF以及Pillow处理图像详解
开发语言·python
森焱森1 小时前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机