Вопрос

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 e.g. inheritance.)

Это было полезно?

Решение 3

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!

Другие советы

I think that you have something like ==(Complex c, Real C) and ==(Complex c, Complex C), of course the compiler won't know which one to choose, so when you compare to a null you have to cast it like c1 == (Complex) null.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top