简体   繁体   English

是否可以使用C ++中的[]运算符访问复数的实部和虚部?

[英]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 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 . 对于类型为complex<T>任何对象zreinterpret_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> 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] 对于任何指向名为pcomplex<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_castT*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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM