问题
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 typecomplex<T>
,reinterpret_cast<T(&)[2]>(z)[0]
is the real part ofz
andreinterpret_cast<T(&)[2]>(z)[1]
is the imaginary part ofz
.For any pointer to an element of an array of
complex<T>
namedp
and any valid array indexi
,reinterpret_cast<T*>(p)[2*i]
is the real part of the complex numberp[i]
, andreinterpret_cast<T*>(p)[2*i + 1]
is the imaginary part of the complex numberp[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