C++/CLI重载的运算符不能通过C#访问
本文关键字:访问 不能 运算符 CLI 重载 C++ | 更新日期: 2025-02-19 11:38:43
我有以下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;
}
};
当我试图从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);
我做错了什么?
您正在重载的==
运算符在C#中不可访问,bool equal1 = a == b
行通过引用比较a
和b
。
二进制运算符被C#中的静态方法覆盖,您需要提供这个运算符:
static bool operator==(MyClass^ a, MyClass^ b)
{
return a->val == b->val;
}
在覆盖==
时,还应覆盖!=
。在C#中,这实际上是由编译器强制执行的。