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;
}
相关推荐
Henry Zhu123几秒前
Qt Model/View架构详解(四):高级特性
开发语言·qt·架构
张祥64228890411 分钟前
误差理论与测量平差基础笔记六
笔记·算法·概率论
txinyu的博客14 分钟前
std::function
服务器·开发语言·c++
多多*30 分钟前
图解Redis的分布式锁的历程 从单机到集群
java·开发语言·javascript·vue.js·spring·tomcat·maven
mjhcsp1 小时前
透彻背包DP:从DFS暴力搜索到动态规划的逐步推导
算法·深度优先·动态规划
电商API&Tina1 小时前
Python请求淘宝商品评论API接口全指南||taobao评论API
java·开发语言·数据库·python·json·php
学嵌入式的小杨同学1 小时前
【嵌入式 C 语言实战】交互式栈管理系统:从功能实现到用户交互全解析
c语言·开发语言·arm开发·数据结构·c++·算法·链表
txinyu的博客1 小时前
static_cast、const_cast、dynamic_cast、reinterpret_cast
linux·c++
多米Domi0111 小时前
0x3f 第40天 setnx的分布式锁和redission,写了一天项目书,光背了会儿八股,回溯(单词搜索)
数据结构·算法·leetcode
乐迪信息1 小时前
乐迪信息解决港口船型识别难题!AI算法盒子检测船舶类型
人工智能·算法·智能电视