首页 > 代码库 > c++语言友元函数和成员函数对运算符重载

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;}