如何在 C++/CLI 中正确地进行运算符重载?
How to correctly do operator overloading in C++/CLI?
在我的 class 中,我有这样的东西:
public ref class Something {
public:
// some methods
operator double();
}
Something
包装了 third-party DLL 中的内容,该 DLL 在其 header 中具有完全相同的 operator double()
。编译器现在抱怨未解析的标记:MyNamespace.Something::op_Implicit
我必须如何在我的实现中定义它?
我尝试了以下三个都不起作用:
double Something::op_Implicit()
- "op_Implicit is not a member"
static double Something::op_Implicit(Something^ s)
- "op_Implicit is not a member"
operator Something::double() {...}
- 一大堆语法错误
内联编写更容易:
public ref class Something {
double yadayada;
public:
operator double() { return yadayada; }
};
如果你不这样做,那么正确的语法是:
Something::operator double() {
return yadayada;
}
这对于 C++/CLI 代码的使用是没问题的,但是如果你想将转换函数公开给其他语言,那么你应该声明它 static:
public ref class Something {
double yadayada;
public:
static operator double(Something^ arg) {
return arg->yadayada;
}
};
前缀 explicit
关键字以避免意外转换并强制客户端代码使用强制转换。
在我的 class 中,我有这样的东西:
public ref class Something {
public:
// some methods
operator double();
}
Something
包装了 third-party DLL 中的内容,该 DLL 在其 header 中具有完全相同的 operator double()
。编译器现在抱怨未解析的标记:MyNamespace.Something::op_Implicit
我必须如何在我的实现中定义它?
我尝试了以下三个都不起作用:
double Something::op_Implicit()
- "op_Implicit is not a member"static double Something::op_Implicit(Something^ s)
- "op_Implicit is not a member"operator Something::double() {...}
- 一大堆语法错误
内联编写更容易:
public ref class Something {
double yadayada;
public:
operator double() { return yadayada; }
};
如果你不这样做,那么正确的语法是:
Something::operator double() {
return yadayada;
}
这对于 C++/CLI 代码的使用是没问题的,但是如果你想将转换函数公开给其他语言,那么你应该声明它 static:
public ref class Something {
double yadayada;
public:
static operator double(Something^ arg) {
return arg->yadayada;
}
};
前缀 explicit
关键字以避免意外转换并强制客户端代码使用强制转换。