Ati*_*liz 5 c++ operators multiplying complex-numbers
以下代码无法编译
#include <iostream>
#include <cmath>
#include <complex>
using namespace std;
int main(void)
{
const double b=3;
complex <double> i(0, 1), comp;
comp = b*i;
comp = 3*i;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有错误:'3*i'中的'operator*'不匹配这里有什么问题,为什么我不能乘以立即常数?b*我的作品.
这个std::complex类有点愚蠢...定义这些以允许自动升级:
// Trick to allow type promotion below
template <typename T>
struct identity_t { typedef T type; };
/// Make working with std::complex<> nubmers suck less... allow promotion.
#define COMPLEX_OPS(OP) \
template <typename _Tp> \
std::complex<_Tp> \
operator OP(std::complex<_Tp> lhs, const typename identity_t<_Tp>::type & rhs) \
{ \
return lhs OP rhs; \
} \
template <typename _Tp> \
std::complex<_Tp> \
operator OP(const typename identity_t<_Tp>::type & lhs, const std::complex<_Tp> & rhs) \
{ \
return lhs OP rhs; \
}
COMPLEX_OPS(+)
COMPLEX_OPS(-)
COMPLEX_OPS(*)
COMPLEX_OPS(/)
#undef COMPLEX_OPS
Run Code Online (Sandbox Code Playgroud)
在第一行:
comp = b*i;
Run Code Online (Sandbox Code Playgroud)
编译器调用:
template<class T> complex<T> operator*(const T& val, const complex<T>& rhs);
Run Code Online (Sandbox Code Playgroud)
其实例如下:
template<> complex<double> operator*(const double& val, const complex<double>& rhs);
Run Code Online (Sandbox Code Playgroud)
在第二种情况下,没有适当的模板int,因此实例化失败:
comp = 3.0 * i; // no operator*(int, complex<double>)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8877 次 |
| 最近记录: |