operator+,-,*,/ (std::complex)

来自cppreference.com
< cpp‎ | numeric‎ | complex
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);
(12)

为复数运算和混合复数/标量运算实现二元运算符。将标量当做拥有等于参数的实部和设为零的虚部的复数。

1-3) 返回其参数的和
4-6) 返回从 lhs 减去 rhs 的结果
7-9) 将参数相乘
10-12) lhs 除以 rhs

目录

[编辑] 参数

lhs, rhs - 参数:两个复数,或一个复数与一个拥有匹配类型的标量( floatdoublelong double

[编辑] 返回值

1-3) complex<T>(lhs) += rhs
4-6) complex<T>(lhs) -= rhs
7-9) complex<T>(lhs) *= rhs
10-12) complex<T>(lhs) /= rhs

[编辑] 注意

因为模板实参推导不考虑隐式转换,这些运算符不能用于整数/复数混合运算。所有情况下,标量必须与复数的底层类型拥有相同类型。

[编辑] 示例

#include <iostream>
#include <complex>
int main()
{
    std::complex<double> c2(2, 0);
    std::complex<double> ci(0, 1);
 
    std::cout << ci << " + " << c2 << " = " << ci+c2 << '\n'
              << ci << " * " << ci << " = " << ci*ci << '\n'
              << ci << " + " << c2 << " / " << ci << " = " << ci+c2/ci << '\n'
              << 1  << " / " << ci << " = " << 1./ci << '\n';
 
//    std::cout << 1.f/ci; // 编译错误
//    std::cout << 1/ci; // 编译错误
}

输出:

(0,1) + (2,0) = (2,1)
(0,1) * (0,1) = (-1,0)
(0,1) + (2,0) / (0,1) = (0,-1)
1 / (0,1) = (0,-1)

[编辑] 参阅

二个复数或一个复数和一个标量的复合赋值
(公开成员函数) [编辑]
对复数运用一元运算符
(函数模板) [编辑]