zoukankan      html  css  js  c++  java
  • c++语言友元函数和成员函数对运算符重载

    #include<iostream>
    using namespace std;
    /******************************************/
    /*use member function to overload operator*/
    /******************************************/
    class RMB{
    public:
        RMB(unsigned int d, unsigned int c);
        RMB operator + (RMB&);
        RMB& operator ++();
        void display(){
            cout <<"use member function overload operator"<<(yuan+jf/100.0) << endl;
        }
    protected:
        unsigned int yuan;
        unsigned int jf;
    };
    RMB::RMB(unsigned int d, unsigned int c){
        yuan = d;
        jf = c;
        while (jf >= 100){
            yuan++;
            jf -= 100;
        }
    }
    RMB RMB::operator + (RMB& s){
        unsigned int c = jf + s.jf;
        unsigned int d = yuan + s.yuan;
        RMB result(d, c);
        return result;
    }
    
    RMB& RMB::operator ++(){
        jf++;
        if (jf >= 100){
            jf -= 100;
            yuan++;
        }
        return *this;
    }
    /******************************************/
    /*use friend function to overload operator*/
    /******************************************/
    class RMBf{
    public:
        RMBf(unsigned int b, unsigned int a);
        friend RMBf operator+(RMBf&, RMBf&);  //two operands  while member function use just one operand
        friend RMBf& operator++(RMBf&);       //one operands  while member function use no operand
        void display(){ cout <<"use friend function to overload operator"<<(yuan+jf/100.0) << endl; }
    protected:
        unsigned int yuan;
        unsigned int jf;
    };
    RMBf::RMBf(unsigned int b, unsigned int a){
        yuan = b;
        jf = a;
        while (jf >= 100){
            yuan++;
            jf -= 100;
        }
    }
    RMBf operator + (RMBf& s1, RMBf& s2){  //needn't class name::operator name, more simple
        unsigned int c = s1.jf + s2.jf;
        unsigned int d = s1.yuan + s2.yuan;
        RMBf result(d, c);
        return result;
    }
    
    RMBf& operator ++(RMBf& s){
        s.jf++;
        if (s.jf >= 100){
            s.jf -= 100;
            s.yuan++;
        }
        return s;
    }
    void main(){
        RMB d1(1, 60);
        RMB d2(2, 50);
        RMB d3(0, 0);
        d3 = d1 + d2;
        ++d3;
        d3.display();
    
        RMBf f1(1, 60);
        RMBf f2(2, 50);
        RMBf f3(0, 0);
        f3 = f1 + f2;
        ++f3;
        f3.display();
        int i;
        cin >> i;
    }
  • 相关阅读:
    XXX系统讨论
    问题账户需求分析
    2017年秋季个人阅读计划
    《软件工程概论》的评价
    第二阶段Day10
    每周总结16
    假期学习记录13(ImageView实现动态加载网络图片)
    假期学习记录12(android与web服务器之间的list/json数组的消息传递)
    假期学习记录11(NavigationView点击事件无效)
    假期学习记录10(自定义AlertDialog,按钮关闭AlertDialog)
  • 原文地址:https://www.cnblogs.com/bruceyo/p/3850733.html
Copyright © 2011-2022 走看看