美文网首页
操作符重载

操作符重载

作者: qyfl | 来源:发表于2017-12-15 22:35 被阅读0次

    操作符重载

    二元操作符

    • 成员函数(含 this )

    由左值调用。 注意返回值必须用引用

    += 的操作把结果加在了 *this 上。

    class A {
    private:
        ...
    
    public:
        A& operator += (const A& r) {
            ...
            return *this;
        }
    };
    
    
    A a();
    A b();
    A c();
    
    // 这时候 a 就是 this,b 就是 r。
    a += b;
    
    // 如果返回值不是引用,这么使用就会出错
    a += b += c;
    
    • 非成员函数(无 this )

    以下实现三个非成员函数的操作符重载

    返回值绝对不能用引用

    a + b 这样的操作会产生一个结果,结果既不是 a 也不是 b。而需要新建一个对象返回。

    如果返回的是引用,函数执行完,新建的对象就消失了(作用域),而引用却把一个不存在的对象的指针传出去了。 这是非常危险的操作!

    // 复数的实现
    class complex {
    private:
        int r, i;
    public:
        ...
        int real() {
            return this->r;
        }
    
        int imag() {
            return this->i;
        }
    };
    
    inline complex&
    operator + (const complex& x, const complex& y) {
        return complex(real(x) + real(y),
                       imag(x) + imag(y));
    }
    
    inline complex&
    operator + (const complex& x, const int y) {
        return complex(real(x) + y, imag(x));
    }
    
    inline complex&
    operator + (const int x, const complex& y) {
        return complex(x + real(y), imag(y));
    }
    
    

    临时对象,不需要对象的名。 类名直接加括号就是临时对象。

    cout << complex(1,2);
    // 这里临时对象就已经消失了
    
    

    具体调用

    complex c1(2,1);
    complex c2;
    
    c2 = c1 + c2;
    c2 = c1 + 5;
    c2 = 7 + c1;
    
    

    对于全局的操作符,只能写成非成员函数

    ostream&
    operator << (ostream& os, const complex& x) {
        return os << real(x) << "," << imag(x) ;
    }
    

    一元操作符

    • 成员函数
    inline complex
    complex::operator - () {
        return complex(-read(this), -imag(this));
    }
    
    • 非成员函数
    inline complex
    operator - (const complex& x) {
        return complex(-real(x), -image(x));
    }
    
    
    • 使用方法
    complex c1(1, 2);
    
    cout << -c1;
    

    参数传递

    相关文章

      网友评论

          本文标题:操作符重载

          本文链接:https://www.haomeiwen.com/subject/erdjwxtx.html