我如何将overload()运算符作为前缀?

0 c++

我想在两个与距离相关的类之间实现显式类型转换.我需要重载()作为前缀使用它像:

class1=(class2)class2_object;
Run Code Online (Sandbox Code Playgroud)

Dan*_*vil 5

查看用户定义的转换.

例:

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...
}
Run Code Online (Sandbox Code Playgroud)

使用C++ 11,您可以使用关键字explicit来避免意外隐式转换(即Y y3 = x;):

     explicit operator Y() const { return ...; } 
Run Code Online (Sandbox Code Playgroud)