我正在编写一个程序,需要实现的一件事是过载>>
操作员一次以一次读取点。我尝试了什么:
std::istream& operator >>(std::istream& is, const Point& point)
{
double temp;
is >> temp;
point.setx(temp);
is.ignore(3,';');
is >> temp;
point.sety(temp);
is.ignore(3,';');
}
它某种程度上未能在VS2019中编译(如果很重要的话(,并说没有操作员>>
接受std::istream
&double
作为参数。任何类型的temp
仍然存在问题。它是int
或char*
,不取决于我是从istream
还是从ifstream
阅读。
这种行为的原因是什么?
也许您忘记了#include <iostream>
?没有这些,您希望像您所引用的那样收到一条错误消息。
解决此问题后,我希望看到其他几个警告/错误。首先,即使operator>>
似乎正在修改已通过的Point
(这是预期的(,您也可以通过point
通过CC_11。您可能要删除const
。
第二,您已声明您的operator>>
返回std::istream &
,但未能返回任何内容。您可能想在结束之前添加return is;
。
此代码编译:
#include <iostream>
struct Point {
double x;
double y;
void setx(double x_) { x = x_; }
void sety(double y_) { y = y_; }
};
std::istream& operator >>(std::istream& is, Point& point)
{
double temp;
is >> temp;
point.setx(temp);
is.ignore(3,';');
is >> temp;
point.sety(temp);
is.ignore(3,';');
return is;
}