PDA

View Full Version : C++ Different forms of the same thing


unknown
2006.06.20, 04:35 PM
For example If I wanted to write a complex number class, and of course I want to deal with normal and polar forms.
I've got a list of functions I can do in normal form, and another list I can do in polar form.

I would want it to call the function if it can in the form its currently in, but convert it to the other form and call the function if it can't.

so that means I suppose ill want ComplexNumber, and then PolarComplexNumber which is a subclass of ComplexNumber, as would be NormalComplexNumber.
but how can my instance of ComplexNumber (which is either a PolarComplexNumber or NormalComplexNumber) know what functions it can and cant call?
How can ComplexNumber convert itself?
What other ways could there be to do this?

ravuya
2006.06.20, 04:44 PM
Have you considered using templates?

I'm assuming you know about polymorphism using virtual methods already.

OneSadCookie
2006.06.20, 05:49 PM
If you just want complex numbers, you could use the built-in support for them :p

#include <complex>

complex<float> var;

Jones
2006.06.21, 07:21 PM
If you just want complex numbers, you could use the built-in support for them :p

#include <complex>

complex<float> var;

What exactly makes a number "complex"? Are we talking scientific notation or power expressions?

OneSadCookie
2006.06.21, 07:30 PM
http://en.wikipedia.org/wiki/Complex_Number

ermitgilsukaru
2006.07.05, 08:20 AM
I can't see a reason to support both forms. Normal and polar forms of complex numbers are the same thing, just different representations. There exist no complex numbers that can be represented in one form but not the other.

A better solution, I think, is to have only one internal representation, but have conversion functions to / from the other representation.

Where it's easier to perform calculations in the other form you can convert to the alternate form at the beginning of the function and convert back when the calculations are done.

No subclassing needed, no typecasting, just one class.

The best solution is still simply using <complex>.

unknown
2006.07.05, 02:15 PM
it a hypothetical example because I wanted to understand C++ class structure better :mad:

Taxxodium
2006.07.05, 03:03 PM
I wanted to understand C++ class structure better :mad:

What's so difficult about it? It shouldn't be any harder than understanding ObjC classes, only there are way more caveats in C++.