C++如何重构操作符

C++和C一样有很多的操作符,如表示逻辑运算的&,|,~,!以及表示数字运算的+,-,*,/,++,–和表示判断的==,&&,||等等。但是在C中这些符号只能用于处理特定类型的数据。但是在C++中可以对部分的操作符重载,已达到操作自定义的类型的数据。C++中可以重载的操作符有:

用途 符号
算术运算 +,-,*,/
自增自减 ++,–
比较 ==,!=,>,<.<=,>=
逻辑判断 &&
输入输出 >>,<<
赋值 =,+=,-=,*=,/=,<<=,>>=,&=
位逻辑 &,^,~,<<,>>
其他 ->,new,delete

等。
下面举几个简单的例子来解释如何使用操作符重载手法。

  1. 复数相加:
    在C++中可以用一个类来表示复数,但是要想将两个复数想加,就必须要在类中重写一个方法,为了简便,可以直接对“+”操作符直接将两个复数相加。
#include <iostream>

using namespace std;

class Complex{
    int real;
    int imag;
public:
    Complex(int x, int y):real(x),imag(y){}

    int getReal()const{
        return real;
    }

    int getImag()const{
        return imag;
    }

    Complex operator+(Complex& b){   //在类中重构“+”运算符,传入需要相加的对象
        Complex c(this->real+b.getReal(), this->imag+b.getImag()); //创建一个新的类,并将二者的实部加实部虚部加虚部
        return c;  //返回这个新的对象
}

};


int main(){
    Complex a(2,3);  //创建两个对象
    Complex b(4,5);
    Complex c = a + b;  //这样的,对象c就可以直接写成a+b了
    cout << "the first complex number: " << a.getReal() << " + " << a.getImag() << "i" << endl;
    cout << "the second complex number: " << b.getReal() << " + " << b.getImag() << "i" << endl;
    cout << "the result of plus 2 complex number: " << c.getReal() << " + " << c.getImag() << "i" << endl;
}

以上就直接重构了"+"操作符,大大的简化了代码的内容。同样的输出结果的时候代码太复杂了,同理也可以对输出符进行重载:

#include <iostream>
#include <sstream>

using namespace std;

class Complex{
    int real;
    int imag;
public:
    Complex(int x, int y):real(x),imag(y){}

    int getReal()const{
        return real;
    }

    int getImag()const{
        return imag;
    }

    Complex operator+(Complex& b){   //在类中重构“+”运算符,传入需要相加的对象
        Complex c(this->real+b.getReal(), this->imag+b.getImag()); //创建一个新的类,并将二者的实部加实部虚部加虚部
        return c;  //返回这个新的对象
}

};


ostream& operator<<(ostream& ss, Complex& x){  //重载输出函数时需要将输出流ostream作为参数传入。同样的如果是对输入函数重载则需要将输入流instream'传入
    ss << x.getReal() << " + " << x.getImag() << "i" << endl;
    return ss;

}

int main(){
    Complex a(2,3);  //创建两个对象
    Complex b(4,5);
    Complex c = a + b;  //这样的,对象c就可以直接写成a+b了
    cout << "the first complex number: " << a.getReal() << " + " << a.getImag() << "i" << endl;
    cout << "the second complex number: " << b.getReal() << " + " << b.getImag() << "i" << endl;
    cout << "the result of plus 2 complex number: " << c.getReal() << " + " << c.getImag() << "i" << endl;
    cout << "\n===========================================\n";
    //通过对输出操作符重载后使代码变得更加简洁
    cout << "the first complex number: " << a;
    cout << "the second complex number: " << b;
    cout << "the result of plus 2 complex number: " << c;
}

这里需要注意的是,重载“+”时是写在类里面的而对输出流进行重载则是写成一个全局函数。如果无法理解的话,可以想象成对类中方法的调用。也可以写成:

Complex c = a.operator+(b);

这样就是对类中的方法的调用,另外一个对象以参数的方式传入。同样的也可以对其他的操作符做重载。比如复数相乘:

Complex operator*(Complex& c){
        Complex x(this->real * c.getReal() - this->imag * c.getImag(), this->real * c.getImag() + this->imag * c.getReal());
        return x;
    }

猜你喜欢

转载自blog.csdn.net/WJ_SHI/article/details/100670573