gpt4 book ai didi

c++ - 你如何访问 vector 对象的成员变量并重载它?

转载 作者:行者123 更新时间:2023-11-28 04:03:20 25 4
gpt4 key购买 nike

我有一个名为 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>没有成员变量xy . point做。这些是句法问题。更重要的问题是:如何填充 std::vector<point>通过从文件中读取对象?

我可以想到以下选项:

  1. 不要假设 point 的数量要在输入流中找到的对象。阅读尽可能多point对象并将它们添加到 std::vector<point> .

  2. 假设只有已知数量的 point对象——可以硬编码或通过其他方式获得。在这种情况下,读取所有它们(假设它们可以成功读取)并将它们添加到 std::vector<point> 中。 .

  3. 读取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);
}
}

关于c++ - 你如何访问 vector 对象的成员变量并重载它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150767/

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