gpt4 book ai didi

c++ 运算符重载 += 有效但 << 无效

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:41 25 4
gpt4 key购买 nike

我原以为 += 和 << 会一样工作,但是 << 不知何故不起作用。

这是我的代码:

#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

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

我在这里错过了什么?

最佳答案

这个:{10, 20}是一个花括号初始化列表。它不是表达式。因此,它只能出现 in specific pieces of C++ grammar .

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

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

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

关于c++ 运算符重载 += 有效但 << 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55886871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com