Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator std::string() const?

Can somebody tell me what precisely

operator std::string() 

stands for?

like image 355
Johnny Avatar asked Jun 15 '10 11:06

Johnny


People also ask

What is const std :: string?

The data type const string& literally means “a reference to a string object whose contents will not be changed.” There are three ways to pass things around (into and out of functions) in C++: 1. Pass by value - a copy of the original object is created and passed.

Does STD string have operator?

std::string::operator= Assigns a new value to the string, replacing its current contents.


2 Answers

It is a conversion operator that allows the object to be explicitly or implicitly casted to std::string. When such a cast occurs, the operator is invoked and the result of the cast is the result of the invocation.

As an example of an implicit cast, suppose you had a function that accepted type std::string or const std::string&, but not the given object type. Passing your object to that function would result in the conversion operator being invoked, with the result passed to the function instead of your type.

like image 106
Michael Aaron Safyan Avatar answered Oct 06 '22 00:10

Michael Aaron Safyan


It is a cast operator. Any class that defines this type can be used anywhere a std::string is required. For instance,

class Foo { public:     operator std::string() const { return "I am a foo!"; } }; ... Foo foo; std::cout << foo; // Will print "I am a foo!". 

Cast operators are almost always a bad idea, since there is invariably a better way to achieve the same result. In the above case, you are better off defining operator<<(std::ostream&, const Foo&).

like image 23
Marcelo Cantos Avatar answered Oct 05 '22 23:10

Marcelo Cantos