I'm working on a wrapper class for char[]
in c++. Something like a String
. Now I want to get a value from the object name. For example:
void main() {
String str;
str = "Hello";
cout << str;
}
so the str
return a character array
, and cout
can print it on the screen. How can I achieve this in my class? (By the way, I know there is already a string class. This is an exercise for Data Structures
lesson)
This is probably what you mean:
std::ostream & operator << (std::ostream & os, const String & s)
{
return os << s.get_char_pointer();
}
Of course you will need to change get_char_pointer
to whatever works for your String
.
You are looking in the wrong direction. You do not need str
to return a character array (which of course it can't anyway). While technically you can define a conversion operator on your String
class, it is not recommended, since it can have an unintended effect.
Instead, overload operator<<
, giving your class as it's second argument, and perform streaming there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.