I came across the following code and the method of the class confused me
class X
{
......
operator string () const {return "X"}
......
}
Normally the return type is in front of the method. I would appreciate it if someone could explain what this statement does and details regarding this statement
A conversion operator is a special kind of member function that converts a value of a class type to a value of some other type. It typically looks like this:
operator type() const;
where type
represents a type. In your example, it's used to implicitly convert a value of class X
to a string
.
This is not an operator()
that returns a string
written in a strange way (as you probably thought), it is an implicit conversion operator that can be used to covert the X
type to a string
type:
X a;
string B = static_cast<string>(a);
Also, take a look at this question .
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.