简体   繁体   中英

toString function or (std::string) cast overload in c++

I am writing a class which I want to be converted into a string.

Should I do it like this:

std::string toString() const;

Or like this:

operator std::string() const;

What way is more accepted?

The classes that have a "string" representation in the standard library (like std::stringstream, for example) use .str() as a member function to return a text. If you want to be able to use your class into generic code as well, better to use the same convention ( toString is " Javanese " and ToString " Sharpish ").

About the use of a conversion operator, that makes sense only if your class is specifically designed to interwork with strings in string expressions (converting to a string is in fact a "promotion", like a int becoming long implicitly).

If your class "demotes" into a string (loses information in doing so), better to have the cast operator explicit ( explicit operator std::string() const ).

If it is unrelated with string semantics, and just has to be occasionally converted, consider explicitly named functions.

Note that, if a is a variable, the semantics you have to think about its usage are:

a.str();       // invoking a member function 
               // mimics std::stringstream, and std::match_results 

to_string(a);  // by means of a free function 
               // mimics number-to-text conversions 

std::string(a) // by means of an explicit cast operator 
               // mimics std::string construction

If your class has nothing to do with strings, but only has to participate in I/O, then consider the idea not to convert to string, but to write to a stream, by means of a...

friend std::ostream& operator<<(std::ostream& stream, const yourclass& yourclass)

so that you can do...

std::cout << a;

std::stringstream ss;
ss << a;   // this makes a-to-text, even respecting locale informations.

...maybe even without the need to allocate any string-related memory.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM