dexter
dexter

Reputation: 13

How can I overload () operator as prefix?

I want to implement the explicit type conversion between two distance-related classes. I need to overload the () as a prefix to use it like:

class1=(class2)class2_object;

Upvotes: 0

Views: 70

Answers (1)

Danvil
Danvil

Reputation: 22981

Look at user-defined conversion.

Example:

struct Y {};

struct X {
     operator Y() const { return ...; } 
};

int main() {
    X x;
    Y y1 = static_cast<Y>(x); // uses conversion operator
    Y y2 = (Y)x; // also possible, but don't use C-style casts in C++!
    Y y3 = x; // even this is possible...
}

With C++11 you can use the keyword explicit to avoid accidental implicit casting (i.e. Y y3 = x;):

     explicit operator Y() const { return ...; } 

Upvotes: 5

Related Questions