运算符重载(++ --)

#include<iostream>
using namespace std;


class F{
int n;
int d;
private:
void reduce()
{
int mcd = maxcd(n<0?-n:n,d);
if(mcd != 1) n/=mcd,d/=mcd;
}
public:
static int maxcd(int a,int b)//静态成员函数 工具函数 不依赖于某个对象
{//没有当前对象 没有this
if(0 == a) return b;
else{
return maxcd(b%a,a);
}
}
F(int n = 0,int d = 1):n(n),d(d){}


friend ostream& operator<<(ostream& o,const F& f)
{
o<<f.n<<'/'<<f.d;
return o;
}
F& operator++(){n+=d;return *this;}//前++
F operator++(int){F old(*this);n += d;return old;}//后++带int参数 为哑元函数
friend F& operator--(F& f){f.n -= f.d;return f;}
friend F operator--(F& f,int){F old(f);f.n -= f.d;return old;}
operator double(){return 1.0*n/d;}
operator bool(){return n != 0;}
};
void fun(F a){cout<<a<<endl;}
int main()
{
F f1(2,5),f2(4,9),f3(17,3);
cout<<++f1<<endl;//f1.operator++();
cout<<f2++<<endl;//f2.operator++(0);
cout<<"f1 = "<<f1<<",f2 = "<<f2<<endl;
cout<<--f3<<endl;//operator--(f3)
cout<<f3--<<endl;//operator--(f3,0)
cout<<"f3 = "<<f3<<endl;
cout<<double(f1)<<endl;//f1.operator double();
cout<<boolalpha<<(bool)f3<<endl;//f3.operator bool();
cout<<F(5)<<endl;
cout<<(F)3<<endl;
fun(7);
}
C++中的运算符重载是指对C++中的运算符进行重新定义,使得原本的运算符可以用于自定义的数据类型。其中,重载运算符++是一种常见的运算符重载。下面是两种重载运算符++的方法: 1. 前置单目运算符重载++ 前置单目运算符重载++是指在变量前面使用++运算符时,重载运算符的函数会被调用。下面是一个示例代码: ```cpp class MyInt { public: int value; MyInt(int v): value(v) {} MyInt& operator++() { ++value; return *this; } }; int main() { MyInt a(1); ++a; cout << a.value << endl; // 输出:2 return 0; } ``` 在上面的代码中,我们定义了一个MyInt类,并在该类中重载了前置单目运算符++。在main函数中,我们创建了一个MyInt对象a,并对其进行了++运算。由于我们重载了++运算符,因此在执行++a时,会自动调用MyInt类中的operator++函数,从而实现了对a.value的自增。 2. 后置单目运算符重载++ 后置单目运算符重载++是指在变量后面使用++运算符时,重载运算符的函数会被调用。下面是一个示例代码: ```cpp class MyInt { public: int value; MyInt(int v): value(v) {} MyInt operator++(int) { MyInt tmp(value); ++value; return tmp; } }; int main() { MyInt a(1); a++; cout << a.value << endl; // 输出:2 return 0; } ``` 在上面的代码中,我们同样定义了一个MyInt类,并在该类中重载了后置单目运算符++。在main函数中,我们创建了一个MyInt对象a,并对其进行了++运算。由于我们重载了++运算符,因此在执行a++时,会自动调用MyInt类中的operator++函数,从而实现了对a.value的自增。需要注意的是,由于后置单目运算符++需要返回原始值,因此我们需要在operator++函数中创建一个临时对象tmp,***
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值