[英]Is it possible to access the real and imaginary parts of a complex number with the [] operator in C++
I'm using the <complex>
library in C++. 我在C ++中使用<complex>
库。 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()
. 我想使用myComplexNum[0]
代替myComplexNum.real()
和myComplexNum[1]
代替myComplexNum.imag()
。
I tried to do it using MingW 4.5.2, and I receive the error: no match found for 'operator[]'
. 我尝试使用MingW 4.5.2进行此操作,但收到错误消息: 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. 我现在确实需要使用[]运算符,因为否则我将不得不更改数百行代码。
As per here in C++11: 根据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
. 对于类型为complex<T>
任何对象z
,reinterpret_cast<T(&)[2]>(z)[0]
是z
的实数部分,而reinterpret_cast<T(&)[2]>(z)[1]
是z
的虚部。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]
对于任何指向名为p
的complex<T>
数组元素和任何有效数组索引i
指针,reinterpret_cast<T*>(p)[2*i]
是复数p[i]
的实部,并且reinterpret_cast<T*>(p)[2*i + 1]
是复数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. 您不能使用std::complex<T>
来执行此操作,但是如果确实需要,可以将自己reinterpret_cast
为T*
或T(&)[2]
并在其上使用operator[]
。
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. 然后在需要的地方使用get(c, 0)
和get(c, 1)
。
Nope. 不。
You could derive from std::complex<>
and inherit constructors and add an overridden operator[]
, but I would advise against it. 您可以从std::complex<>
派生并继承构造函数,并添加一个重写的operator[]
,但我建议不要这样做。
You will have to wrap std::complex in your complex class: 您将必须在复杂类中包装std :: complex:
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. 这对于获取涉及std :: complex为Complex的操作/函数的结果是必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.