bbazso
bbazso

Reputation: 2049

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

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?

Upvotes: 16

Views: 18123

Answers (5)

Jonathan M Davis
Jonathan M Davis

Reputation: 38267

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

operator string();

defined can be converted to a string.

Upvotes: 9

fogo
fogo

Reputation: 304

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.

Upvotes: 2

kennytm
kennytm

Reputation: 523164

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.

Upvotes: 35

Mike Burton
Mike Burton

Reputation: 3020

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

Upvotes: -2

ZeissS
ZeissS

Reputation: 12135

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

Upvotes: 2

Related Questions