looking for a design pattern for complex numbers class in c++

88 Views Asked by At

I'm using complex numbers for learning design patterns. I'm currently using an abstract class:

namespace abstract{
    class complex{
        public:
            virtual ~complex() = 0;
            virtual double re() const = 0;
            // some other virtual function
    };    
};

namespace cartesian{
    class complex : public abstract::complex{
        public:
            complex(){}
            ~complex(){}
            double re() const override{return re_;};
            //... other functions
        private:
             double re_;
             double im_;

            // other
        
    };

};

namespace polar{
    class complex{
        /// polar complex numbers....
    };
};

I want to being able to write in the main:

cartesian::complex c(1,2);
polar::complex p(3,PI);
exponential::complex q = exp(c) + p;
print(q)

The thing is that I will have to write a lot of assignment operators with forward declarations for each class. So is there a way to make all representations of the complex class the same type, and having just different constructors? Something like pimpl with different pointers for each implementation or something with templates i don't know.

1

There are 1 best solutions below

0
A M On

There is no common design pattern for this task.

And polymorphism is for me not a design pattern. It is a integral part of the C++ language.

And of course it is clear that everything is already existing in C++. So, you know std::complex already. I am not sure if you know about std::literals::complex_literals . With that you can write intuitive things like:

#include <iostream>
#include <complex>
 
int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << std::abs(c) << '\n';
    std::complex<float> z = 3.0f + 4.0if;
    std::cout << "abs" << z << " = " << std::abs(z) << '\n';
}

Example taken from CPP reference


You could select one representation of a complex number and then convert all other forms into it. Then you can do all operations with one data type.

The only things that you would need to integrate then are more constructors and more assignment operators. But for that it would be better to use complex-literals.

So, my recommendation. Do not use polymorphism. It is too complex and too slow for this task.

Please consider.

For educational purposes, you may of course implement your solution. For this, use custom literals or a parser . . .