什么是C ++中的无名临时对象及其在递减运算符重载中的使用?

先决条件:运算符重载及其规则

有时为了减少代码大小,我们创建了类的无名临时对象。

当我们想从类的成员函数返回一个对象而不创建一个对象时,为此:我们只调用类的构造函数并将其返回给调用函数,并且有一个对象来保存构造函数返回的引用。

这个概念被称为无名临时对象,使用该概念我们将实现一个用于递减运算符重载的C ++程序。

看程序:

using namespace std;
#include <iostream>

class Sample
{
	//私有数据部分
	private:
	int count;
	
	public:
	//默认构造函数
	Sample()
	{ count = 0;}      

	//参数化的构造函数
	Sample(int c)
	{ count = c;}      

	//运算符重载函数定义
	Sample operator--()
	{ 
		--count;
		//返回样本数
		//这里没有新对象, 
		//Sample(count):通过传递count的值来构造
		//并返回值(递减值)
		return Sample(count);
	}
	
	//打印值
	void printValue()
	{
		cout<<"Value of count : "<<count<<endl;
	}
};

//主程序
int main(){
	int i = 0;
	Sample S1(100), S2;

	for(i=0; i< 5; i++)
	{    
		S2 = --S1;

		cout<<"S1 :"<<endl;
		S1.printValue();

		cout<<"S2 :"<<endl;
		S2.printValue();
	}
	return 0;    
}

输出结果

S1 :
Value of count : 99
S2 :
Value of count : 99
S1 :
Value of count : 98
S2 :
Value of count : 98
S1 :
Value of count : 97
S2 :
Value of count : 97
S1 :
Value of count : 96
S2 :
Value of count : 96
S1 :
Value of count : 95
S2 :
Value of count : 95

在此程序中,我们在重载成员函数中使用了无名临时对象

在这里,我们没有在成员函数内创建任何对象。我们只是在调用构造函数,然后将递减后的值返回给调用函数。