在 C++ 中直接读取结构

Reading directly to struct in C++

假设我有一些结构,例如 Rectangle:

struct Rectangle
{
    int x0, x1, y0, y1;
};

是否可以创建一个 Rectangle 结构以便能够调用:

Rectangle rec;
cin >> rec;

?我觉得应该是可以弄出来的,只是我经验不够

免责声明

我不是在找这个:

cin >> rec.x0 >> rec.x1 >> rec.y0 >> rec.y1;

您可以使用:

Rectangle rec;
cin >> rec;

如果您定义了适当的 operator>> 函数。

std::istream& operator>>(std::istream& in, Rectangle& rec)
{
   return (in >> rec.x0 >> rec.x1 >> rec.y0 >> rec.y1);
}

如果不允许您定义这样的函数,那么您将无法使用您想要使用的语法。

是的,最好的解决方案是为 Rectangle 重载 operator>>:

struct Rectangle
{
    int x0, x1, y0, y1;
};

istream& operator>>(istream& s, Rectangle& r)
{
    s >> r.x0 >> r.x1 >> r.y0 >> r.y1;
    return s;
}