为什么是复杂的< double> ;?* int在C ++中未定义吗? [英] Why is complex<double> * int not defined in C++?
问题描述
C ++程序
#include <complex>
#include <iostream>
int main()
{
std::complex<double> z(0,2);
int n = 3;
std::cout << z * n << std::endl;
}
产生一个错误:'z * n'中的'operator *'不匹配.为什么?
yields an error: no match for ‘operator*’ in ‘z * n’. Why?
我正在使用g ++ 4.4.1进行编译.也许编译器只是遵循C ++标准,在这种情况下,我的问题是:为什么标准不允许这样做?
I'm compiling with g++ 4.4.1. Perhaps the compiler is just following the C++ standard, in which case my question is: why does the standard not allow this?
推荐答案
这有效:
#include <complex>
#include <iostream>
int main()
{
std::complex<double> z(0,2);
double n = 3.0; // Note, double
std::cout << z * n << std::endl;
}
因为复数由双精度数组成,所以它乘以双精度数.查看声明:
Because complex is composed of doubles, it multiplies with doubles. Looking at the declaration:
template <typename T>
inline complex<T> operator*(const complex<T>&, const T&);
(以下内容感谢 dribeas ).在模板推导过程中,不允许编译器进行隐式类型转换,因此通过传递 T 为 double
的 complex
,然后传递另一个 T 为 int
的 complex
,当尝试匹配将 T 视为 double
的函数时,会导致第二个参数不匹配,反之亦然.
(The following is thanks to dribeas) The compiler is not allowed to make implicit type conversions during template deduction, so by passing a complex
with T being double
, and then another T being int
, when trying to match the function treating T as double
causes the second argument to mis-match, and vice-versa.
对于您要工作的东西,必须定义一个类似于以下内容的函数:
For what you want to work, it would have to have a function defined similar to this:
template <typename T, typename U>
inline std::complex<T> operator*(std::complex<T> lhs, const U& rhs)
{
return lhs *= rhs;
}
哪个允许该函数采用不同的类型,从而允许在调用 operator * =
时进行强制转换.
Which allows the function to take differing types, which allows the cast to be done when calling operator*=
.
这篇关于为什么是复杂的< double> ;?* int在C ++中未定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!