如何在C ++中使用非成员或自由函数重载减量运算符?
先决条件:运算符重载及其规则
在这里,我们将实现一个C++程序,该程序将演示使用非成员函数或自由成员函数进行运算符重载(递减)。
注意:这种类型的非成员函数将访问类的私有成员。因此,该功能必须为好友类型(好友功能)。
看程序:
using namespace std;
#include <iostream>
//示例类演示操作符重载
class Sample
{
//私有数据成员
private:
int value;
public:
//参数化构造函数
Sample(int c)
{ value = c;}
//使运算符重载声明为
//友元函数
friend Sample operator--(Sample &S, int);
//打印值
void printValue()
{
cout<<"Value is : "<<value<<endl;
}
};
//运算符重载函数定义
Sample operator--(Sample &S,int)
{
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 : 99 Value is : 98 Value is : 97 Value is : 96 Value is : 95
热门推荐
10 小学毕业父母简短祝福语
11 幼儿生日祝福语模板简短
12 新娘妈妈的祝福语简短
13 邻居聚会祝福语大全简短
14 十条祝福语简短
15 给同学祝福语的简短
16 过年祝福语简短祝妈妈
17 祝女儿简短祝福语大全
18 恩师诗词祝福语简短大全