complex number operator question

J

jraul

Suppose you have a complex number class, and you overload conversions
to double by only taking the real part. You also overload operator* to
do complex multiplication.

You then write:

complex a(...);
complex b(...);

complex c = a*b;

Then the compiler complains that it is ambiguous because it doesn't
know if you want complex*complex, or to do the case to double first,
and do double*double. I would think that it would be obvious that
complex*complex should be chosen. Other than explicit casts is there a
way to handle this?
 
V

Victor Bazarov

jraul said:
Suppose you have a complex number class, and you overload conversions
to double by only taking the real part. You also overload operator*
to do complex multiplication.

You then write:

complex a(...);
complex b(...);

complex c = a*b;

Then the compiler complains that it is ambiguous because it doesn't
know if you want complex*complex, or to do the case to double first,
and do double*double. I would think that it would be obvious that
complex*complex should be chosen. Other than explicit casts is there
a way to handle this?

Make sure that the operator* is actually a better choice for the
compiler, i.e. it doesn't have to perform any conversions before
calling it. I think it is possible. Read the FAQ 5.8, I think it
deals with your case.

V
 
Z

Zealot Zuo

jraul said:
Suppose you have a complex number class, and you overload conversions
to double by only taking the real part. You also overload operator* to
do complex multiplication.

You then write:

complex a(...);
complex b(...);

complex c = a*b;

Then the compiler complains that it is ambiguous because it doesn't
know if you want complex*complex, or to do the case to double first,
and do double*double. I would think that it would be obvious that
complex*complex should be chosen. Other than explicit casts is there a
way to handle this?

After all I don't think the code above is good.
Though you may find a way to make non-conversion calculation the
"preferred" way for one compiler, you can't ensure that other compilers
accept it. Explicit cast is extremely recommend to prevent ambiguous
overloaded-function call. Scott Meyers mentioned this in his Effective
C++.
So write the cast-constructor as explicit, it is good for your program.

Sincerely,
Z.Z.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top