当我比较三个物体时,为什么要返回参考?

时间:2016-07-06 13:08:59

标签: c++ operator-overloading

我要学习运算符重载,我不会得到任何东西。 当我这样做时:

    class Point
    {
public:
    void show(){ cout << "the point is(" << _x << ", " << _y << ")" << endl;}
    void print(){ _x = 1; _y = 1; }
    void operator+=(const Point &other){
        _x = other._x + 100;
        _y = other._y + 100;
    }

private:
    int _x;
    int _y;
};

int main()
{
    Point p1;
    Point p2;
    p1 +=p2;
    p2.show();
    getchar();
}

它的工作。但当我把它改为:

Point p1;
Point p1;
Point p2;
Point p3;
p1 +=p2 +=p3;

它没有,我需要返回(* this)。为什么?如果有人能向我解释,我会很高兴..谢谢:)。

3 个答案:

答案 0 :(得分:3)

当你这样做时

p1 +=p2;

您实际上正在致电

p1.operator+=(p2)

它会返回void,但它不应该(请参阅Assignment operators),但这不是问题所在,因为您还没有使用返回值。< / p>

但是当你做的时候

p1 += p2 += p3;

实际上

p1.operator+=(p2.operator+=(p3))

现在返回void是个问题,因为operator + =需要一个值作为参数。

答案 1 :(得分:2)

您需要在此处返回引用的原因是p2 +=p3p2添加到p3后未评估为operater+=。它评估的是Point void的返回值void。您无法将p1添加到p2 +=p3,因此您会收到错误。

查看p2.operator+=(p3)的另一种方式是p2。在这里,我们可以清楚地看到我们没有获得p2.operator+=(p3),而是获得var path = require('path'); var webpack = require('webpack'); module.exports = { entry: './src/app/app.jsx', output: { path: __dirname, filename: 'app.js' }, port: 9090, devServer: { contentBase: './src', hot: true, port: 9090, publicPath: '/assets/', noInfo: false }, resolve: ['.js', '.jsx', ''], module: { loaders: [ { test: /.jsx$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react'] } } ] }, }; 返回的内容。

这就是我们返回引用的原因。它允许我们像你想要的那样将结果链接在一起。如果你没有返回引用,那么你必须打破链。

答案 2 :(得分:1)

您的运算符+ =返回类型为void。

void operator+=(const Point &other);
^^^^^

因此,此运算符的调用不能用于运算符的其他调用+ =。

否则它看起来像

Point p;

p += void;

运算符的有效定义可能类似于

Point & operator +=( const Point &other )
{
    _x += other._x;
    _y += other._y;

    return *this;
}