Tutorial :what does the operator string() { some code } do?



Question:

I have the following code in a class:

operator string() {          return format("CN(%d)", _fd);  }  

And wanted to know what this operator does.

I am familiar with the usual string operators:

bool operator==(const string& c1, const string& c2);  bool operator!=(const string& c1, const string& c2);  bool operator<(const string& c1, const string& c2);  bool operator>(const string& c1, const string& c2);  bool operator<=(const string& c1, const string& c2);  bool operator>=(const string& c1, const string& c2);  string operator+(const string& s1, const string& s2 );  string operator+(const Char* s, const string& s2 );  string operator+( Char c, const string& s2 );  string operator+( const string& s1, const Char* s );  string operator+( const string& s1, Char c );  string& operator+=(const string& append);  string& operator+=(const Char* append);  string& operator+=(const Char  append);  ostream& operator<<( ostream& os, const string& s );  istream& operator>>( istream& is, string& s );  string& operator=( const string& s );  string& operator=( const Char* s );  string& operator=( Char ch );  Char& operator[]( size_type index );  const Char& operator[]( size_type index ) const;  

... but not this one?


Solution:1

operator Type() { ... }  

is the (implicit) conversion operator. For example, if class Animal implements operator string(), then the code

Animal a;  ...  do_something_with ( (string)a );  

will become something like

do_something_with ( (Animal::operator string)(&a) );  

See http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr385.htm for some more examples.


Solution:2

It's overloading the cast operator. A class which has the function

operator string();  

defined can be cast to a string.


Solution:3

If just returns a string represantation of your current object, e.g. for printing it on the console.


Solution:4

It is an automatic type conversion operator. This class you are talking about can be implicitly converted to a string. This link might help you with a few more examples.


Solution:5

That would appear to be a cast-to-string operator for a decimal number type.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »