[英]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 . 查看用户定义的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;
): 在C ++ 11中,您可以使用关键字
explicit
以避免意外的隐式转换(即Y y3 = x;
):
explicit operator Y() const { return ...; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.