C++的运算符重载详解(2)

在进行运算符重载的时候我们需要注意两个问题:
  1、在运算符的操作数,必须至少含有一个自定义类型的变量。
  2、尽量使用成员函数对运算符进行重载,但是有的运算符只能使用友元函数进行重载。
      比如对于"<<" 和“>>”的重载,如下:

class F{
public:
    F(int n = 0, int d = 1):n(n), d(d){}
    friend ostream& operator<<(ostream& os, const F& f){
        os << f.n << '/' << f.d;
        return os;
    }
    friend istream& operator>>(istream& is, F& f){
        char ch;
        is >> f.n >> ch >> f.d;
        return is;
    }
    F operator*(const F& o)const{
        return F(o.n * n, o.d * d);
    }
    friend F operator/(const F& obj1, const F& obj2);
private:
    int n;
    int d;
};
 
F operator/(const F& f1, const F& f2)
{
    return(f1.n * f2.d, f1.d * f2.n);
}
int main(int ac, char *av[])
{
    F f1(1,2);
    F f2(3,4);
 
    cout << f1 << "*" << f2 << "=" << f1*f2 << endl;
    cout << f1 << "/" << f2 << "=" << f1/f2 << endl;
    cout << "enter 2 number : \n";
    cin >> f1 >> f2;
    cout << "f1 = " << f1 << endl;
    cout << "f2 = " << f2 << endl;
     
    return 0;
}       
运行结果:
[root@anna-laptop overload_operator]# ./muldiv
[1/2]*[3/4]=[3/8]
[1/2]/[3/4]=[4/6]
enter 2 number : 
123 / 456
234/ 7645
f1 = [123/456]
f2 = [234/7645]

以上的操作符全是对于双目运算符的重载,下面简单介绍几个单目运算符的例子,如"++"和"--"
因为++有前置++和后置++两种,--也是如此,对于前置++我们直接将++后的结果直接返回即可,对于后置++,为了方便区别于前置++,通常认为++后面仍然含有一个int类型的数组。进行如下操作:
class A{
public:
    A(int data = 0):data(data){}
    friend ostream& operator<<(ostream& os, const A& a){
        os << a.data;
        return os;
    }
    friend istream& operator>>(istream& is, A& a){
        is >> a.data;
        return is;
    }
    // 前置 ++;
    friend A& operator++(A& a){
        a.data += 10;
        return a;
    }
    // 前置 --
    A& operator--(){
        data -= 10;
        return *this;
    }
    // 后置 ++;
    friend A operator++(A& a, int){
        A old(a);
        a.data += 5;
        return old;
    }
    // 后置 --
    A operator--(int){
        A old(*this);
        data -= 5;
        return old;
    }
private:
    int data;
};
int main(int ac, char *av[])
{
    A a1(100);
    A a2(100);
 
    cout << "a1 = " << a1 << endl; 
    cout << "a2 = " << a2 << endl; 
    ++a1;
    --a2;
    cout << "++a1 = " << a1 << endl; 
    cout << "--a2 = " << a2 << endl; 
    cout << "a1++ = " << a1++ << endl; 
    cout << "a2-- = " << a2-- << endl; 
    cout << "a1 = " << a1 << endl; 
    cout << "a2 = " << a2 << endl; 
    return 0;
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/91f91137b8241478a751ed37783beab4.html