你如何访问向量对象的成员变量并重载它?
How do you access vector object's member variable and overload it?
我有一个名为 point
的结构,我正在尝试重载 istream
运算符,但我无法访问 x
和 y
变量。
struct point {
int x;
int y;
point(int x = 0, int y = 0)
: x{x}, y{y}
{}
};
std::istream& operator>>(std::istream& is, const std::vector<point> &d){
return is >> d.x >> d.y; //error const class std::vector<point> has no member named x or y
}
is >> d.x >> d.y
不起作用,因为 d
是 std::vector<point>
类型,而不是 point
。 std::vector<point>
没有成员变量x
或y
。 point
确实如此。这些是句法问题。更重要的问题是:如何通过从文件中读取对象来填充 std::vector<point>
?
我可以想到以下选项:
不要假设要在输入流中找到的对象数量 point
。尽可能多地读取 point
个对象并将它们添加到 std::vector<point>
.
假设只有已知数量的 point
个对象——可以硬编码或通过其他方式获得。那样的话,就全部读取(假设能读取成功),添加到std::vector<point>
.
从流本身读取 point
个对象。这假设可以从流中读取的 point
s 的数量也可以从流中获得。然后,读取预期数量的point
个对象(假设能读取成功),添加到std::vector<point>
.
在所有这些情况下,您都需要能够从流中读取 point
。为此,我建议,
std::istream& operator>>(std::istream& is, point& p)
{
return is >> p.x >> p.y;
}
要从流中填充 std::vector<point>
,您必须从第二个参数中删除 const
。你需要
std::istream& operator>>(std::istream& is, std::vector<point>& d)
{
// Implement the appropriate strategy here to read one point object
// at a time and add them to d.
// For the first strategy, you'll need:
point p;
while ( is >> p )
{
d.push_back(p);
}
}
我认为,理想情况下,您应该将运算符重载函数作为友元函数。
我有一个名为 point
的结构,我正在尝试重载 istream
运算符,但我无法访问 x
和 y
变量。
struct point {
int x;
int y;
point(int x = 0, int y = 0)
: x{x}, y{y}
{}
};
std::istream& operator>>(std::istream& is, const std::vector<point> &d){
return is >> d.x >> d.y; //error const class std::vector<point> has no member named x or y
}
is >> d.x >> d.y
不起作用,因为 d
是 std::vector<point>
类型,而不是 point
。 std::vector<point>
没有成员变量x
或y
。 point
确实如此。这些是句法问题。更重要的问题是:如何通过从文件中读取对象来填充 std::vector<point>
?
我可以想到以下选项:
不要假设要在输入流中找到的对象数量
point
。尽可能多地读取point
个对象并将它们添加到std::vector<point>
.假设只有已知数量的
point
个对象——可以硬编码或通过其他方式获得。那样的话,就全部读取(假设能读取成功),添加到std::vector<point>
.从流本身读取
point
个对象。这假设可以从流中读取的point
s 的数量也可以从流中获得。然后,读取预期数量的point
个对象(假设能读取成功),添加到std::vector<point>
.
在所有这些情况下,您都需要能够从流中读取 point
。为此,我建议,
std::istream& operator>>(std::istream& is, point& p)
{
return is >> p.x >> p.y;
}
要从流中填充 std::vector<point>
,您必须从第二个参数中删除 const
。你需要
std::istream& operator>>(std::istream& is, std::vector<point>& d)
{
// Implement the appropriate strategy here to read one point object
// at a time and add them to d.
// For the first strategy, you'll need:
point p;
while ( is >> p )
{
d.push_back(p);
}
}
我认为,理想情况下,您应该将运算符重载函数作为友元函数。