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

c++ operator overloading += works but << doesn't work

本文关键字:lt 不起作用 有效 运算符 重载 C++      更新时间:2023-10-16

我希望 += 和 <<会正常工作,但<<不知何故不起作用。

这是我的代码:

#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

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

我在这里错过了什么?

this: {10, 20} 是一个大括号的初始化列表。它不是一种表达。因此,它只能出现在特定的C++语法中。

例如,大括号初始化列表可以出现在类型名之后,这意味着它们初始化该类型的 prvalue。它们可以显示为函数的参数。并且(在其他几个(它们可以出现在赋值运算符的右侧。

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

<<不是这些特定的地方之一。因此,裸大括号的 init 列表不能出现在<<表达式的任一侧。这与<<表达式将被转换为对operator<<的调用这一事实无关,因此大括号的初始化列表可以被视为函数参数。C++语法根本不允许大括号的初始化列表出现在那里,因此编译器永远不会走得足够远,甚至无法尝试重载解析来确定要调用哪个函数。

<<运算符需要在 lef 端有一个 ostream。 以下是将日期对象流式传输到"cout"所必须执行的操作的 .Net 版本:

#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;
}