简体   繁体   中英

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;

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 (ie Y y3 = x; ):

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM