重载一元运算符

自增++运算符

cpp 复制代码
#include<iostream>
using namespace std;
class CGirl
{
public:
	string name;
	int ranking;
	CGirl() { name = "zhongge"; ranking = 5; }
	void show() const{ cout << "name : "<<name << " , ranking : " << ranking; }

};
int main() {
	CGirl g1;
	g1.show();
	return 0;
}

现在我们重载一个++运算符

cpp 复制代码
#include<iostream>
using namespace std;
class CGirl
{
public:
	string name;
	int ranking;
	CGirl() { name = "zhongge"; ranking = 5; }
	void show() const{ cout << "name : "<<name << " , ranking : " << ranking; }
	void operator++() {
		ranking++;
	}

};
int main() {
	CGirl g1;
	++g1;
	g1.show();
	return 0;
}

main函数里的g1++不行但是++g1就行了;

然而你++(++g)不行,你让你重载函数返回对象的引用就可以了;

cpp 复制代码
#include<iostream>
using namespace std;
class CGirl
{
public:
	string name;
	int ranking;
	CGirl() { name = "zhongge"; ranking = 5; }
	void show() const{ cout << "name : "<<name << " , ranking : " << ranking; }
	 CGirl & operator++() {
		ranking++;
		return *this;
	}

};
int main() {
	CGirl g1;
	++(++g1);
	g1.show();
	return 0;
}

上面这是自增运算符的前置,我们再来个后置的;

c++规定重载自增&自减运算符,如果重载函数有一个int形参,编译器处理后置表达式时将调用这个重载函数。

cpp 复制代码
#include<iostream>
using namespace std;
class CGirl
{
public:
	string name;
	int ranking;
	CGirl() { name = "zhongge"; ranking = 5; }
	void show() const{ cout << "name : "<<name << " , ranking : " << ranking; }
	 CGirl & operator++(int ) {
		ranking++;
		return *this;
	}

};
int main() {
	CGirl g1;
	g1++;
	g1.show();
	return 0;
}

这样就ok了;


整数的话不可以后自增嵌套,前自增嵌套可以;

cpp 复制代码
#include<iostream>
using namespace std;
class CGirl
{
public:
	string name;
	int ranking;
	CGirl() { name = "zhongge"; ranking = 5; }
	void show() const{ cout << "name : "<<name << " , ranking : " << ranking; }
	CGirl& operator++(int ) {
		ranking++;
		return *this;
	}


};
int main() {
	CGirl g1,g2;
	g2=g1++;
	g2.show();
	g1.show();
	return 0;
}
cpp 复制代码
name : zhongge , ranking : 6name : zhongge , ranking : 6
C:\Users\33007\source\repos\ConsoleApplication8\x64\Debug\ConsoleApplication8.exe (进程 9820)已退出,代码为 0。
按任意键关闭此窗口. . .

显然你g1++是后来加,g2应该是g1之前的值而不是增后的值。

所以改一下后++的代码;

cpp 复制代码
CGirl operator++(int ) {
	CGirl tmp = *this;
	ranking++;
	return tmp;
}

函数的返回值不能是引用,成员函数的临时对象不能引用;

cpp 复制代码
name : zhongge , ranking : 5name : zhongge , ranking : 6
C:\Users\33007\source\repos\ConsoleApplication8\x64\Debug\ConsoleApplication8.exe (进程 15512)已退出,代码为 0。
按任意键关闭此窗口. . .

这样功能就对上了;

相关推荐
树叶@17 分钟前
Python数据分析7
开发语言·python
wydaicls21 分钟前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地1 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药
姜君竹1 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
思捻如枫1 小时前
C++数据结构和算法代码模板总结——算法部分
数据结构·c++
奇树谦1 小时前
使用VTK还是OpenGL集成到qt程序里哪个好?
开发语言·qt
嘉陵妹妹1 小时前
深度优先算法学习
学习·算法·深度优先
VBA63371 小时前
VBA之Word应用第三章第十节:文档Document对象的方法(三)
开发语言
老胖闲聊1 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
GalaxyPokemon2 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展