先决条件:运算符重载及其规则
有时为了减少代码大小,我们创建了类的无名临时对象。
当我们想从类的成员函数返回一个对象而不创建一个对象时,为此:我们只调用类的构造函数并将其返回给调用函数,并且有一个对象来保存构造函数返回的引用。
这个概念被称为无名临时对象,使用它我们将实现一个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 : 101 S2 : Value of count : 101 S1 : Value of count : 102 S2 : Value of count : 102 S1 : Value of count : 103 S2 : Value of count : 103 S1 : Value of count : 104 S2 : Value of count : 104 S1 : Value of count : 105 S2 : Value of count : 105
在此程序中,我们在重载成员函数中使用了无名临时对象。
在这里,我们没有在成员函数内创建任何对象。我们只是在调用构造函数,然后将递增的值返回给调用函数。