2017-10-13 48 views
1

我發現複雜的運營商+中MSVC返回非const複雜有關在C++庫中實現Complex的問題?

_TMPLT(_Ty) inline 
    _CMPLX(_Ty) operator+(const _Ty& _Left, 
     const _CMPLX(_Ty)& _Right) 
    { // add complex to real 
    _CMPLX(_Ty) _Tmp(_Left); 
    return (_Tmp += _Right); 
    } 

此外,在cppreference,它也是非const

template< class T > 
complex<T> operator+(const complex<T>& lhs, const complex<T>& rhs); 
(1) 
template< class T > 
complex<T> operator+(const complex<T>& lhs, const T& rhs); 
(2) 
template< class T > 
complex<T> operator+(const T& lhs, const complex<T>& rhs); 
(3) 
template< class T > 
complex<T> operator-(const complex<T>& lhs, const complex<T>& rhs); 
(4) 
template< class T > 
complex<T> operator-(const complex<T>& lhs, const T& rhs); 
(5) 
template< class T > 
complex<T> operator-(const T& lhs, const complex<T>& rhs); 
(6) 
template< class T > 
complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs); 
(7) 
template< class T > 
complex<T> operator*(const complex<T>& lhs, const T& rhs); 
(8) 
template< class T > 
complex<T> operator*(const T& lhs, const complex<T>& rhs); 
(9) 
template< class T > 
complex<T> operator/(const complex<T>& lhs, const complex<T>& rhs); 
(10)  
template< class T > 
complex<T> operator/(const complex<T>& lhs, const T& rhs); 
(11)  
template< class T > 
complex<T> operator/(const T& lhs, const complex<T>& rhs); 

這時,有人認爲,它應該是const

但是,我不能想到這種情況導致非const的必要性。

有人可以告訴我這樣的情況嗎?謝謝

+2

爲什麼*應該*爲const?換句話說,爲什麼'int + int'返回'const int'? – CoryKramer

+4

切勿將代碼張貼爲截圖。 – dandan78

+0

@ dandan78我編輯了截圖。謝謝! – czxyl

回答

2

你誤解了你所關聯的問題和答案。

答案並沒有說明函數的返回值。有關傳遞給函數,並正確參數答案會談表明,參數應該傳遞恆定引用和常量指針,如果該功能沒有發生變異,這些參數

  • 參數應傳遞如果該函數不會改變它們,則爲const引用
  • 如果該函數不改變其從中調用的對象,則應該將函數聲明爲const

沒有理由讓operator + (const T& a , const T& b)返回const對象,這樣做可能會阻止重要的優化。