![](/img/trans.png)
[英]Getting pointers to the real and imaginary parts of a complex vector in C++
[英]Is it possible to access the real and imaginary parts of a complex number with the [] operator in C++
我在C ++中使用<complex>
庫。 是否可以使用[]運算符訪問復數的實部和復雜部分? 我想使用myComplexNum[0]
代替myComplexNum.real()
和myComplexNum[1]
代替myComplexNum.imag()
。
我嘗試使用MingW 4.5.2進行此操作,但收到錯誤消息: no match found for 'operator[]'
。 我現在確實需要使用[]運算符,因為否則我將不得不更改數百行代碼。
根據C ++ 11中的此處 :
對於類型為
complex<T>
任何對象z
,reinterpret_cast<T(&)[2]>(z)[0]
是z
的實數部分,而reinterpret_cast<T(&)[2]>(z)[1]
是z
的虛部。對於任何指向名為
p
的complex<T>
數組元素和任何有效數組索引i
指針,reinterpret_cast<T*>(p)[2*i]
是復數p[i]
的實部,並且reinterpret_cast<T*>(p)[2*i + 1]
是復數p[i]
的虛部
您不能使用std::complex<T>
來執行此操作,但是如果確實需要,可以將自己reinterpret_cast
為T*
或T(&)[2]
並在其上使用operator[]
。
如果可能的話,我建議創建一個訪問器函數:
template <class T>
T & get(std::complex<T> & c, int index)
{
if(index == 0) return c.real();
else return c.imag();
}
然后在需要的地方使用get(c, 0)
和get(c, 1)
。
不。
您可以從std::complex<>
派生並繼承構造函數,並添加一個重寫的operator[]
,但我建議不要這樣做。
您將必須在復雜類中包裝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;
}
這對於獲取涉及std :: complex為Complex的操作/函數的結果是必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.