gpt4 book ai didi

c++ - 重载运算符 i/o 问题

转载 作者:行者123 更新时间:2023-11-28 06:58:29 24 4
gpt4 key购买 nike

我正在尝试重载运算符 >> 但我在尝试编译时出现了一个大错误

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: error: no match for ‘operator>>’ in ‘tmp2 >> 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: In function ‘std::istream& operator>>(std::istream&, const CGPS&)’: test.cpp:448:29: error: cannot call member function ‘bool CGPS::testeur(std::string, std::vector&)’ without object test.cpp:452:23: error: no matching function for call to ‘CGPS::Add(CCoord&) const’ test.cpp:452:23: note: candidate is: test.cpp:106:12: note: CGPS& CGPS::Add(CCoord) test.cpp:106:12: note: no known conversion for implicit ‘this’ parameter from ‘const CGPS*’ to ‘CGPS*’

最佳答案

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

所以你需要实现

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

调用你的实现的语法是

x1 >> tmp2;

这看起来很奇怪。


附录:

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

  1. CGPS 参数不能是const(它是您正在读入的对象,因此您将对其进行修改)。
  2. testeur 显然是 CGPS 的成员函数,因此您应该像 rhs.testeur(str,v) 那样调用它。<

关于c++ - 重载运算符 i/o 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22864771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com