opeartor 关键字重载 实验

来源:互联网 发布:淘宝直通车计划 编辑:程序博客网 时间:2024/05/18 15:57

opeator 用于重载运算符,运算符相当一个函数名。
如果是内联函数第一个参数可以不显示。
注意后置 的参数中 有一个 int ,值返回。前置 ,引用返回。

#include<iostream>#include<cmath>using namespace std;class RMB{             public:            unsigned int jf,yuan;            RMB(unsigned int d,unsigned int c){                jf=c;                yuan=d;                while(jf>100){                    jf-=100;                    yuan++;                }            }            friend RMB operator-(RMB,RMB);            friend RMB operator--(RMB&,int); // 后置 值返回        friend RMB& operator--();             // 前置 引用返回            void disp(){                cout<<yuan+jf/100.0<<endl;            }};RMB& RMB::operator--(){    //  左值操作,返回引用    if(this->jf==0){        this->jf=100;        yuan--;    }    this->jf--;    return *this;}RMB operator-(RMB x,RMB y){    RMB temp(x.yuan-y.yuan,x.jf-y.yuan);    return temp;}RMB operator--(RMB&x,int){    cout<<x.jf<<" "<<x.yuan<<endl;    RMB temp=x;    if(x.jf==0){        x.jf=100;        x.yuan--;    }    x.jf--;    return temp;}int main(){    RMB d1(2,85);    d1.disp();    RMB d2(1,56);    d2.disp();    RMB d3(d1-d2);    cout<<d3.jf<<" "<<d3.yuan<<endl;    RMB d4(100,200);    --d4;    cout<<d4.jf<<" "<<d4.yuan<<endl;    RMB d5(100,200);    d5--;    RMB d6(100,200);    --d6;    cout<<d6.jf<<" "<<d6.yuan<<endl;    return 0;}
0 0