我运行时遇到以下错误。有什么帮助吗?
ambigious overload for ‘operator >> ’ in ‘getfile >> point’
这是我在pp对象中的代码
istream& pp::operator >> (istream& in)
{
//error msg
string msg = "Error. Output from file, String is found instead of integer. Please check file for errors\n";
//ignore everything till next record
in.ignore(256, '[');
//store x cordinate
in >> x;
if(in.fail()){throw msg;}
//ignore everything till next record
in.ignore(256, ',');
//store y cordinate
in >> y;
if(in.fail()){throw msg;}
//ignore the rest of the records till next line
in.ignore(256, '\n');
return in;
}//end of operator >> method
这是我的主要内容
{
ifstream getfile;
//get filename to input data into system
cout << "\nPlease enter filename : ";
cin >> file;
getfile.open(file, ios::in);
pp pointObject();
getfile >> point;
}
这是我的pp.h结构,你们想看看。
class pp
{
public:
//constructor
pp();
pp(int, int);
pp(const Point2D &pd);
//operator overloaded methods
virtual pp operator-(pp pd);
virtual bool operator<(pp pd) const;
virtual bool operator>(pp pd) const;
virtual bool operator==(pp pd);
virtual ostream& operator<<(ostream& o) const;
virtual istream& operator>>(istream& in;
//accessor,mutator methods
int getX() const;
int getY() const;
void setX(int);
void setY(int);
protected:
int x;
int y;
};
#endif
答案 0 :(得分:3)
operator>>
不能是该类的成员,因为这会使参数的顺序错误。您必须考虑所有成员函数(和运算符)的隐式this
参数。
签名应为istream& operator>>(istream& in, pp& point)
,以便在getfile >> point;
中使用。
答案 1 :(得分:0)
operator >>
的定义应为:
istream& operator>>(istream& in, pp &p)
然后,在函数体内,您应该将读取的x
和y
值分配给p.x
和p.y
。
答案 2 :(得分:0)
我建议写一个独立的运算符重载
注意,Re:处理流错误并使用例外,请参阅try/catch throws error
friend istream& pp::operator>> (istream& in, pp& pointObject)
{
//error msg
const string msg = "ErPoint2Dror. Output from file, String is found instead of integer. Please check file for errors\n";
//ignore everything till next record
in.ignore(256, '[');
int x,y;
//store x cordinate
in >> x;
if(in.fail())
{
throw msg;
}
//ignore everything till next record
in.ignore(256, ',');
//store y cordinate
in >> y;
if(in.fail())
{
throw msg;
}
//ignore the rest of the records till next line
in.ignore(256, '\n');
pointObject.x = x;
pointObject.y = y;
return in;
}//end of operator >> method
答案 3 :(得分:0)
重载流运营商的最佳方法是让他们成为朋友。
在你的pp类声明中:
friend istream& operator >>(istream& in, pp& obj);
在你的cpp文件中:
istream& operator>>(istream &in, pp& obj)
{
// Your code
}