Operator Overload

【例4-1-1】Operator Overload(运算符重载)

重载为成员函数

class Complex{
public:
    Complex(double r,double i):real(r),imag(i){}
    Complex operator+ (Complex& c2);
private:
    double real,imag;
};
Complex Complex::operator+(Complex& c2){

    double r = c2.real + this->real;
    double i = c2.imag + this->imag;
    
    return Complex(r, i);
}

【例4-1-2】重载为友元(普通函数)

class Complex{
public:
    Complex(double r,double i):real(r),imag(i){}
    friend Complex operator+ (Complex& c1,Complex& c2);
private:
    double real,imag;
};
Complex operator+(Complex& c1,Complex& c2){
    double r = c1.real + c2.real;
    double i = c1.imag + c2.imag;
    
    return Complex(r, i);
}

【例4-2】如何区分 前置 及 后置 单目运算符

class Clock{
public:
    Clock operator++();      //前置++
    Clock operator++(int);   //后置++
    ...
};

前置++的实现

Clock& Clock::operator++ (){
    s++;
    if(s >= 60){
        s = s-60;
        m++;
        if(m >= 60) {
            m = m-60;
            h = (++h)%24;
        }
    }
    return  *this;
}

后置++的实现

Clock Clock::operator++(int) {
    Clock copy(*this);
    
    ++(*this);
    
    return  copy;
}

【习4-1】重载 [] 运算符,使得:

SafeArray a(100);

a.set(50,1000); ==> a[50] = 1000;

int x = a.get(50); ==> int x = a[50];

【习4-2】重载 << >> 运算符,使得:

Computer computer;

cin >> computer;

cout << computer;

【习4-3】重载 == 运算符,使得:

Computer c1,c2;

if( c1 == c2 )...

The End

目录