c ++运算符重载+ =有效但<<不起作用

问题描述 投票:6回答:2

我期望+ =和<<将起作用,但是<<某种程度上不起作用。

这是我的代码:

#include <iostream>

using namespace std;

struct Pos{
    int x;
    int y;

    void operator+=(Pos vel){
        x += vel.x;
        y += vel.y;
    }
};

struct Obj{
    string name;
    Pos pos;

    void info(){
        cout << name << endl;
        cout << pos.x << ", " << pos.y << endl;
        cout << endl;
    }
    void operator<<(Pos vel){
        pos += vel;
    }
    void operator+=(Pos vel){
        pos += vel;
    }
};


int main(){
    Pos p{10, 20};
    Obj car{"Car", p};
    Obj truck{"Big truck", {40, 20}};

    car.info();
    truck.info();

    //doesn't work
    car << {0, 10};
    //works
    car += {5, 10};
    //works
    car << Pos{0, 10};
    //works
    car += Pos{5, 10};

    car.info();
} 

他们中的大多数都有效,但是car << {0, 10};

表明:

[Error] expected primary-expression before '{' token

我想知道+=<<之间有什么区别以及为什么使用构造函数会起作用。

我在这里错过了什么?

c++ oop operator-overloading
2个回答
7
投票

这个:{10, 20}是一个braced-init-list。这不是表达。因此,它只能出现in specific pieces of C++ grammar

例如,braced-init-lists可以出现在typename之后,这意味着它们初始化该类型的prvalue。它们可以作为函数的参数出现。并且(在其他几个中)它们可以出现在赋值运算符的右侧。

请注意,+=是一个赋值运算符。

<<不是这些特定的地方之一。因此,一个裸的braced-init-list不能出现在<<表达式的任何一侧。这与<<表达式将转换为对operator<<的调用无关,因此braced-init-list可以被认为是函数参数。 C ++语法只是不允许在那里出现braced-init-list,因此编译器永远不会达到甚至尝试重载解析来确定要调用哪个函数。


-1
投票

<<操作符需要左侧的ostream。这里是.Net版本的你要做的流媒体Date对象到“cout”:

#include <iostream>
using namespace std;

class Date
{
    int mo, da, yr;
public:
    Date(int m, int d, int y)
    {
        mo = m; da = d; yr = y;
    }
    friend ostream& operator<<(ostream& os, const Date& dt);
};

ostream& operator<<(ostream& os, const Date& dt)
{
    os << dt.mo << '/' << dt.da << '/' << dt.yr;
    return os;
}

int main()
{
    Date dt(5, 6, 92);
    cout << dt;
}
© www.soinside.com 2019 - 2024. All rights reserved.