简体   繁体   English

定义运算符==时,空值返回“调用不明确”

[英]When defining the operator ==, null value returns “call is ambiguous”

I have custom classes Rational, Real, and Complex. 我有自定义类Rational,Real和Complex。 In Complex I overload operators that allow me to compare a Complex and a Real, or a Complex and a Rational. 在Complex中,重载运算符使我可以比较Complex和Real,或者Complex和Rational。 It would be easy if I could define an implicit cast of a Rational to a Complex, say, but for reasons not worth going into, I can't. 如果我可以定义从Rational到Complex的隐式转换,这很容易,但是由于不值得深入探讨的原因,我做不到。

Therefore I have, among others, 因此,除其他外,我有

==(Complex a, Real b)

and also 并且

==(Real a, Complex b)

Obviously when I try to compare 显然,当我尝试比较时

c==null

I get the error message that the call is ambiguous. 我收到错误消息,该呼叫是模棱两可的。 I saw on a related thread the idea that I could just define ==(Complex a, object b) I had thought of that, but then if I want to allow symmetry, I also need ==(object a, Complex b) in which case a comparison between two complexes will also be ambiguous. 我在一个相关的线程上看到了我可以定义==(Complex a, object b)想法,但是如果我想允许对称,我还需要在其中==(object a, Complex b)在这种情况下,两个复合体之间的比较也将是模棱两可的。

Right now when I check for null I'm having to cast the Complex to an object first. 现在,当我检查null时,我必须首先将Complex转换为对象。 What's a better solution? 有什么更好的解决方案? (I'm hoping for a general solution rather than a solution that depends on any relationship between the classes eg inheritance.) (我希望有一个通用的解决方案,而不是依赖于类之间任何关系(例如继承)的解决方案。)

Why to use the second overload? 为什么要使用第二个过载? Are you sure you cannot use first one for your checks? 您确定不能使用第一个支票吗? There is no "good-looking" solution you are looking for. 您没有正在寻找的“好看”解决方案。

我认为您有==(Complex c, Real C)==(Complex c, Complex C) ,当然编译器不会知道选择哪个,因此当您与null比较时,您必须像c1 == (Complex) null

I should probably post that I don't think there is a solution, and I just decided to forsake symmetry and go with ==(Complex a, object b). 我可能应该发贴说我不认为有解决方案,我只是决定放弃对称性,并使用==(Complex a,object b)。 Thanks to everyone who posted! 感谢所有张贴的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM