What can the use of the operator keyword in C ++ mean here?

This is an application written in C ++. Under what circumstances does this line make sense for any of you, in the context of the definition of struct ( stream is a member variable of type FILE* ):

 operator FILE*(){return stream;} 

I went through the debugger trying to figure this out, but I can't get this line of code to activate. I have never come across an operator overload keyword in this way. What can this line of code do?

+6
source share
1 answer

This is an implicit conversion operator .

Implicit conversion operators allow a type that otherwise could not be directly converted to a destination type, and this can be done. They have the following syntax, where Foo is the class of the object that is implicitly converted, and Bar is the target class:

 class Foo{ public: operator Bar(); // allow implicit conversion of Foo objects to Bar }; 

A more common instance of this operator is converting an object to a boolean value as a reality check. This can be seen with standard library streams and smart pointers.

It should be noted that there is a syntax variation that prevents the existing conversion, and instead makes the conversion explicit:

 class Foo{ public: explicit operator Bar(); // allow explicit conversion of Foo objects to Bar }; 

This prevents bites from the compilation program when you accidentally load type A , which can convert to type B into a function that accepts only B Of course, this may be what you are going to do, but it is not always, and they decided to add it to the language to help people in need of an explicit transformation.

With the explicit conversion operator, you can create an object from the source object either through the construction (using it when building the object of the target type) or by explicit casting: B{A}

+9
source

All Articles