直接读取C 的结构

Reading directly to struct in C++

本文关键字:结构 读取      更新时间:2023-10-16

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

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

是否可以以一种能够致电的方式创建矩形结构:

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

如果不允许您定义这样的功能,则不能使用要使用的语法。

是的,最好的解决方案是 Rectangleoperator>>

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