无法将整数添加到 std::complex<double>
Cannot add integer to std::complex<double>
我正在尝试向 complex<double>
添加整数,但我做不到。这是代码的相关部分:
using dcomplex = std::complex<double>;
dcomplex j = dcomplex(0,1);
// dcomplex r = 1+j;//this line is not compiling
dcomplex r = 1.0+j;//ok
我理解为什么 j+=1
没有编译,因为 operator+=
在 complex
中重载并且没有隐式转换 int->double
。但是 operator+
并没有在复合体中超载(我在那里没有找到它)。所以它在其他地方超载了(在哪里?我找不到它)并且因此 int
应该隐式转换为 double
。但事实并非如此。为什么?
它是一个非成员函数,因为标量在左边。 (http://en.cppreference.com/w/cpp/numeric/complex/operator_arith3)。您可以将整数转换为双精度或 j.value_type
.
来自cppreference the overloads for std::complex::operator+
是
template< class T >
complex<T> operator+( const complex<T>& lhs, const complex<T>& rhs);
template< class T >
complex<T> operator+( const complex<T>& lhs, const T& rhs);
template< class T >
complex<T> operator+( const T& lhs, const complex<T>& rhs);
当类型推导发生时会发生冲突,因为它将 T
计算为 double
和 int
。由于 T
不能同时存在,因此会产生错误。
我正在尝试向 complex<double>
添加整数,但我做不到。这是代码的相关部分:
using dcomplex = std::complex<double>;
dcomplex j = dcomplex(0,1);
// dcomplex r = 1+j;//this line is not compiling
dcomplex r = 1.0+j;//ok
我理解为什么 j+=1
没有编译,因为 operator+=
在 complex
中重载并且没有隐式转换 int->double
。但是 operator+
并没有在复合体中超载(我在那里没有找到它)。所以它在其他地方超载了(在哪里?我找不到它)并且因此 int
应该隐式转换为 double
。但事实并非如此。为什么?
它是一个非成员函数,因为标量在左边。 (http://en.cppreference.com/w/cpp/numeric/complex/operator_arith3)。您可以将整数转换为双精度或 j.value_type
.
来自cppreference the overloads for std::complex::operator+
是
template< class T >
complex<T> operator+( const complex<T>& lhs, const complex<T>& rhs);
template< class T >
complex<T> operator+( const complex<T>& lhs, const T& rhs);
template< class T >
complex<T> operator+( const T& lhs, const complex<T>& rhs);
当类型推导发生时会发生冲突,因为它将 T
计算为 double
和 int
。由于 T
不能同时存在,因此会产生错误。