Mau*_*wer 4 c# c++-cli operator-overloading
我有以下C++/CLI类:
public ref class MyClass
{
public:
int val;
bool operator==(MyClass^ other)
{
return this->val == other->val;
}
bool Equals(MyClass^ other)
{
return this == other;
}
};
Run Code Online (Sandbox Code Playgroud)
当我尝试从C#验证两个实例MyClass是否相等时,我得到了错误的结果:
MyClass a = new MyClass();
MyClass b = new MyClass();
//equal1 is false since the operator is not called
bool equal1 = a == b;
//equal2 is true since the comparison operator is called from within C++\CLI
bool equal2 = a.Equals(b);
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
Mar*_*age 10
==您正在重载的运算符无法在C#中访问,并且行bool equal1 = a == b比较a和b引用.
二进制运算符被C#中的静态方法覆盖,您需要提供此运算符:
static bool operator==(MyClass^ a, MyClass^ b)
{
return a->val == b->val;
}
Run Code Online (Sandbox Code Playgroud)
覆盖时,==你也应该覆盖!=.在C#中,这实际上是由编译器强制执行的.
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |