假设我有一些结构,例如一个Rectangle
struct Rectangle
{
int x0, x1, y0, y1;
};是否可以以一种只需调用以下命令的方式创建矩形结构:
Rectangle rec;
cin >> rec;?我认为这应该是可能的,但我没有足够的经验。
免责声明
我不是在找这个:
cin >> rec.x0 >> rec.x1 >> rec.y0 >> rec.y1;发布于 2015-05-05 21:51:52
您可以使用:
Rectangle rec;
cin >> rec;如果您定义了一个适当的operator>>函数。
std::istream& operator>>(std::istream& in, Rectangle& rec)
{
return (in >> rec.x0 >> rec.x1 >> rec.y0 >> rec.y1);
}如果不允许定义这样的函数,则不能使用要使用的语法。
发布于 2015-05-05 21:53:16
是的,最好的解决方案是重载operator>>以实现Rectangle
struct Rectangle
{
int x0, x1, y0, y1;
};
istream& operator>>(istream& s, Rectangle& r)
{
s >> r.x0 >> r.x1 >> r.y0 >> r.y1;
return s;
}https://stackoverflow.com/questions/30063834
复制相似问题