Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 429
bbazso Avatar asked Feb 10 '10 18:02

bbazso


1 Answers

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.

like image 64
kennytm Avatar answered Sep 28 '22 17:09

kennytm