如何使用C ++中的非成员或自由函数重载预递增运算符?
先决条件:运算符重载及其规则
在这里,我们将实现一个C++程序,该程序将演示使用非成员或自由成员函数进行运算符重载(预递增)。
注意:这种类型的非成员函数将访问类的私有成员。因此,该函数必须为友元类型(友元函数)。
考虑一下程序:
using namespace std;
#include <iostream>
//示例类演示操作符重载
class Sample
{
//私有数据成员
private:
int value;
public:
//参数化构造函数
Sample(int c)
{ value = c;}
//运算符重载声明
//友元函数
friend Sample operator++(Sample &S);
//函数打印值
void printValue()
{
cout<<"Value is : "<<value<<endl;
}
};
//友元函数 (operator overloading) definition
Sample operator++(Sample &S)
{
++S.value;
return S;
}
//主程序
int main(){
int i = 0;
//对象声明,
//这里参数化的构造函数将被称为
Sample S1(100);
for(i=0;i<5;i++)
{
//运算符重载
++S1;
S1.printValue();
}
return 0;
}输出结果
Value is : 101 Value is : 102 Value is : 103 Value is : 104 Value is : 105