C++常见操作符的重载

来源:互联网 发布:2017笔记本推荐 知乎 编辑:程序博客网 时间:2024/06/02 01:35

1. 什么是操作符的重载

操作符重载,计算机学科概念,就是把已经定义的、有一定功能的操作符进行重新定义,来完成更为细致具体的运算等功能。操作符重载可以将概括性的抽象操作符具体化,便于外部调用而无需知晓内部具体运算过程。
也就是说我们在以前操作符的基础上进行修改,重新定义,使一个操作符能够操作一个对象以及多个对象。

2. 常见操作符的重载

为了演示,我们来定义一个复数类

class Complex{    friend ostream& operator<<(ostream& out, const Complex& com);    friend istream& operator>>(istream& in, Complex& com);public:    Complex(double real=0.0,double image=0.0)  //构造函数    :_real(real), _image(image)    {    }    Complex& operator =(const Complex& com)    //赋值运算符的重载    {        _real = com._real;        _image = com._image;        return *this;    }    Complex& operator++()                      //前置++    {        _real++;        _image++;        return *this;    }    Complex operator++(int)                    //后置++    {        Complex tmp(*this);        _real++;        _image++;        return tmp;    }private:    double _real;    double _image;};ostream& operator<<(ostream& out,const Complex& com)  //输出运算符{    out << com._real << "+" << com._image << "i";    return out;}istream& operator>>(istream& in, Complex& com)        //输入运算符{    in >> com._real;    in >> com._image;    return in;}int main(){    Complex c;    cin >> c;    cout << c << endl;    Complex c1=c++;    cout << c << endl;    cout << c1 << endl;    Complex c2=++c;    cout << c << endl;    cout << c2 << endl;    return 0;}

需要注意的是 后置++,在使用的时候先将对象c1的值赋给另一个对象c2,然后这个对象c1本身在进行自增。

    Complex operator++(int)    {        Complex tmp(*this);        _real++;        _image++;        return tmp;    }

所以,先将这个对象c1本身保存在一个临时构建出来的对象tmp,然后将对象c1自身增加,最终返回tmp。
而且前置++和后置++需要形成重载,所以在参数类型放入一个 int使其形成重载。

还需要注意的是输入输出操作符的重载 cout/cin,要写成友元函数的形式。

    friend ostream& operator<<(ostream& out, const Complex& com);    friend istream& operator>>(istream& in, Complex& com);

如果直接在类中重载,我们使用的时候,就会与原操作符不同。

c1<<cout//与原操作符不同c1>>cin//与原操作符不同

我们将其写成友元函数,在类中只定义,返回值需要输入输出流的引用istream& in/ostream& out,方便连续输入输出。

原创粉丝点击