【发布时间】:2013-11-10 14:43:54
【问题描述】:
我有一个Point2D 类,我正在尝试重载输入运算符 >>
class Point2D
{
public:
Point2D(int,int);
int getX();
int getY();
void setX(int);
void setY(int);
double getScalarValue();
bool operator < ( const Point2D& x2) const
{
return x < x2.x;
}
friend istream& operator >> (istream&,Point2D);
protected:
int x;
int y;
double distFrOrigin;
void setDistFrOrigin();
};
在我的主要功能之外
#include <iostream>
#include <fstream>
#include "Line2D.h"
#include "MyTemplates.h"
#include <string>
#include <set>
using namespace std;
istream operator >> (istream& is , Point2D p2d)
{
string p;
getline(is,p,'\n');
int position = p.find(", ");
string k = p.substr(0,position);
if ( k == "Point2D")
{
string x = p.substr(10,1);
int x_coordinate = atoi(x.c_str()); // atoi(x.c_str()) convert string x to int
p2d.setX(x_coordinate);
}
return is;
}
在我的 int main() 中
int main()
{
fstream afile;
string p;
afile.open("Messy.txt",ios::in);
if (!afile)
{
cout<<"File could not be opened for reading";
exit(-1);
}
Point2D abc;
afile>>abc;
set<Point2D> P2D;
P2D.insert(abc);
set<Point2D>::iterator p2 = P2D.begin();
while ( p2 != P2D.end() )
{
cout<<p2->getX();
p2++;
}
}
我不明白为什么会出错:
c++ 禁止声明没有类型的 istream
我已经包含了 iostream , fstream ,使用命名空间 std ,我不知道是什么问题
【问题讨论】:
-
您需要通过引用返回
std::istream(它不能被复制,即按值返回不起作用)并通过引用传递您的参数(否则您将修改本地对象)。在你的声明中(在课堂上)你应该使用std::istream而不是istream。 -
对不起,我是 c++ 新手,什么意思?
-
istream在std命名空间中,所以你需要friend std::istream& operator >> (std::istream&, Point2D&);不要使用using namespace std;,反正这很糟糕,并且会导致你的代码有些混乱。跨度> -
当我已经有“使用命名空间标准”时,我需要包含什么 std::
-
您可能不在
using namespace std需要它的地方(为了安全起见,不要在任何地方这样做),而且您可能包含也可能不包含必需的标题。
标签: c++ overloading istream