首页 > 编程语言 > 详细

c++语言友元函数和成员函数对运算符重载

时间:2014-07-17 14:13:48      阅读:267      评论:0      收藏:0      [点我收藏+]
#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;
}

c++语言友元函数和成员函数对运算符重载,布布扣,bubuko.com

c++语言友元函数和成员函数对运算符重载

原文:http://www.cnblogs.com/bruceyo/p/3850733.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!