Reputation: 315
I build a new string class in C++ called UString
, I think it should support cin
and cout
, so I want to overload <<
and >>
operator, but my Visual Studio told me that I put too many argument in that function.
What should I do?
My first code like this:
std::istream &operator>>(UString ustr)
{
std::istream istr(nullptr);
istr >> ustr.str;
return istr;
}
I didn't got any error if I compile the class without use this function,but if I use it by: cin>>ustr;
, the compiler told me that there is no match ver of this >>
operator. So I searched it in Google and changed it like that:
std::ostream &operator<< (std::ostream& ostr, const UString ustr)
{
ostr << ustr.str;
return ostr;
}
But, the pre-check told me that there are too many arguments in it, it can not be compiled successfully also.
My IDE is Visual Studio 2017
, C++ ver is set to C++17
.
std::ostream &operator<< (std::ostream& ostr, const UString ustr)
{
ostr << ustr.str;
return ostr;
}
//>>
std::istream &operator>>(UString ustr)
{
std::istream istr(nullptr);
istr >> ustr.str;
return istr;
}
After overloading, it should support use like this:
UString ustr;
cin>>ustr;
cout<<ustr<<endl;
Upvotes: 0
Views: 92
Reputation: 1209
std::istream&>>
and <<
operators are binary operators (they have two arguments). When you overload this operators you can make it either member function (inside your class) or free function.
Code x >> y;
will be transformed either to x.operator>>(y);
(in case of member function) or to operator>>(x, y);
(in case of free function).
As you want to overload operator with left argument of type that you can't modify (stream) you should overload it as a free function.
class UString { ... };
std::istream& operator>>(std::istream& s, UString& str) { ... }
std::ostream& operator<<(std::ostream& s, Ustring& str) { ... }
Upvotes: 1