我正在尝试重载运算符>>但是当我尝试编译
时,我遇到了很大的错误std::istream& operator>>(std::istream & is)
{
string str;
is>>str;
vector<Cord> v;
cout<<str<<endl;
bool test=testeur(str, v);
if (test)
{
for (unsigned int i=0;i<v.size();i++)
table.push_back(v[i]);
}
return is;
}
我的主要:
istringstream tmp2 ( "(0,0) > (0,1)" );
tmp2 >> x1;
我收到此错误:test.cpp:473:9:错误:'tmp2&gt;&gt;中'运算符&gt;&gt;'不匹配X1’ test.cpp:473:9:注意:候选人是:
现在我试过了:
friend std::istream& operator>>(std::istream & is, const CGPS & rhs)
{
string str;
is>>str;
vector<CCoord> v;
cout<<str<<endl;
bool test=testeur(str, v);
if (test)
{
for (unsigned int i=0;i<v.size();i++)
rhs. Add (v[i]);
}
return is;
}
我收到此错误:
test.cpp:在函数'std :: istream&amp;运算符&gt;&gt;(std :: istream&amp;,const CGPS&amp;)': test.cpp:448:29:错误:无法调用成员函数'bool CGPS :: testeur(std :: string,std :: vector&amp;)' test.cpp:452:23:错误:没有用于调用'CGPS :: Add(CCoord&amp;)const'的匹配函数 test.cpp:452:23:注意:候选人是: test.cpp:106:12:注意:CGPS&amp; CGPS ::加入(CCoord) test.cpp:106:12:注意:从'const CGPS *'到'CGPS *'的隐式'this'参数没有已知的转换
答案 0 :(得分:1)
>>
运算符必须是自由函数,因为它的左侧是流。
所以你需要实现
std::istream& operator>>(std::istream& is, YourClass& x);
调用您的实现的语法是
x1 >> tmp2;
看起来很奇怪。
附录:
您在更新的代码中犯了两个错误:
CGPS
参数不能是const
(它是您正在阅读的对象,因此您将对其进行修改)。testeur
显然是CGPS
的成员函数,因此您应该将其称为rhs.testeur(str,v)
。答案 1 :(得分:0)
运营商&gt;&gt; function不能是类的成员函数,因为第一个参数必须是istream而不是this。
试试这个:
friend std::istream& operator>>(std::istream & is, MyClass & rhs)
{
input the data here (you have access to private data)
return is;
}
或者如果您只需要MyClass的公共成员来访问您需要的数据,您可以在同一名称空间中将其作为独立的自由函数。如果没有“朋友”,宣言看起来会一样。它应该出现在类的声明之外,您可能需要将其内联。
澄清:你有(至少)三种选择:
对于所有这些选择,运营商&gt;&gt;函数是独立的,不是类的成员。