重载运算符i / o问题

时间:2014-04-04 13:52:16

标签: c++ io overloading istream

我正在尝试重载运算符>>但是当我尝试编译

时,我遇到了很大的错误
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'参数没有已知的转换

2 个答案:

答案 0 :(得分:1)

>>运算符必须是自由函数,因为它的左侧是流。

所以你需要实现

std::istream& operator>>(std::istream& is, YourClass& x);

调用您的实现的语法是

x1 >> tmp2;

看起来很奇怪。


附录:

您在更新的代码中犯了两个错误:

  1. CGPS参数不能是const(它是您正在阅读的对象,因此您将对其进行修改)。
  2. 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的公共成员来访问您需要的数据,您可以在同一名称空间中将其作为独立的自由函数。如果没有“朋友”,宣言看起来会一样。它应该出现在类的声明之外,您可能需要将其内联。

澄清:你有(至少)三种选择:

  • 将该函数声明(并定义)为友元函数。它甚至不是集体成员 虽然定义出现在类声明中
    • 通过此选项,您可以访问班级中的私人数据。
  • 将函数声明(并定义)为与类(在同一名称空间中)相同的头文件中的内联函数,但在类声明之外,并且仅使用类上的公共方法来设置读取的值。
  • 在与该类相同的头文件中声明该函数。在cpp文件中定义函数体。区别在于函数不是内联的。

对于所有这些选择,运营商&gt;&gt;函数是独立的,不是类的成员。