简体   繁体   中英

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

I have custom classes Rational, Real, and Complex. In Complex I overload operators that allow me to compare a Complex and a Real, or a Complex and a 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.

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.

Right now when I check for null I'm having to cast the Complex to an object first. 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). Thanks to everyone who posted!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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