Reputation: 49
I am trying to overload operator >> but I have a big error when I try to compile
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;
}
my main:
istringstream tmp2 ( "(0,0) > (0,1)" );
tmp2 >> x1;
I get this error: test.cpp:473:9: error: no match for ‘operator>>’ in ‘tmp2 >> x1’ test.cpp:473:9: note: candidates are:
now I tried this:
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;
}
and I get this error:
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*’
Upvotes: 0
Views: 303
Reputation: 9434
The operator >> function cannot be a member function of the class because the first argument must be the istream rather than this.
Try this:
friend std::istream& operator>>(std::istream & is, MyClass & rhs)
{
input the data here (you have access to private data)
return is;
}
or if you only need public members of MyClass to access the data you need, you can make it a stand-alone free function in the same namespace. The declaration would look the same without the "friend". It should appear outside the declaration of the class, and you probably need to make it inline.
Clarification: You have (at least) three choices:
For all of these choices, the operator >> function is stand-alone, not a member of the class.
Upvotes: 0
Reputation: 66371
The >>
operator has to be a free function, since it's left hand side is the stream.
So you need to implement
std::istream& operator>>(std::istream& is, YourClass& x);
The syntax for calling your implementation would be
x1 >> tmp2;
which looks really strange.
Addendum:
You made two errors in your updated code:
CGPS
parameter can't be const
(it's the object you're reading into, so you'll be modifying it).testeur
is apparently a member function of CGPS
, so you should call it like rhs.testeur(str,v)
.Upvotes: 1