Is it possible to access the real and imaginary parts of a complex number with the [] operator in C++

孤街浪徒 提交于 2019-12-11 12:43:47

问题


I'm using the <complex> library in C++. Is it possible to access the real and complex parts of a complex number using the [] operator? I want to use myComplexNum[0] instead of myComplexNum.real() and myComplexNum[1] instead of myComplexNum.imag().

I tried to do it using MingW 4.5.2, and I receive the error: no match found for 'operator[]'. I really need to use the [] operator for now, because otherwise I would have to change hundreds of lines of code.


回答1:


Nope.

You could derive from std::complex<> and inherit constructors and add an overridden operator[], but I would advise against it.




回答2:


As per here in C++11:

For any object z of type complex<T>, reinterpret_cast<T(&)[2]>(z)[0] is the real part of z and reinterpret_cast<T(&)[2]>(z)[1] is the imaginary part of z.

For any pointer to an element of an array of complex<T> named p and any valid array index i, reinterpret_cast<T*>(p)[2*i] is the real part of the complex number p[i], and reinterpret_cast<T*>(p)[2*i + 1] is the imaginary part of the complex number p[i]

You can't do this with a std::complex<T> but if you really have to you can reinterpret_cast to a T* or T(&)[2] and use operator[] on that.

If possible, I would suggest creating an accessor function:

    template <class T>
    T & get(std::complex<T> & c, int index)
    {
        if(index == 0) return c.real();
        else return c.imag();
    }

and then use get(c, 0) and get(c, 1) where needed.




回答3:


You will have to wrap std::complex in your complex class:

class Complex {
   public:
   explicit Complex(std::complex& value) : m_value(value) {}
   ...
   operator std::complex& () { return m_value; }
   operator const  std::complex& () const { return m_value; }
   ...
   private:
   std::complex m_value;
}

This will be necessary for getting the results of operations/functions involving std::complex as Complex.



来源:https://stackoverflow.com/questions/22919357/is-it-possible-to-access-the-real-and-imaginary-parts-of-a-complex-number-with-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!