【问题标题】:Multiplying complex with constant in C++在 C++ 中将复数与常数相乘
【发布时间】:2010-04-15 18:11:31
【问题描述】:

以下代码编译失败

#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;
}

与 错误:‘3 * i’中的‘operator*’不匹配 这里有什么问题,为什么我不能乘以立即常数? b*i 有效。

【问题讨论】:

    标签: c++ operators complex-numbers multiplication


    【解决方案1】:

    在第一行:

    comp = b*i;
    

    编译器调用:

    template<class T> complex<T> operator*(const T& val, const complex<T>& rhs);
    

    实例如下:

    template<> complex<double> operator*(const double& val, const complex<double>& rhs);
    

    第二种情况,没有合适的模板int,所以实例化失败:

    comp = 3.0 * i; // no operator*(int, complex<double>)
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 太棒了,这比写一大堆运算符要好得多
      • 为什么 std 中默认不存在?是不是因为同时使用一些 complex、complex、complex 和 complex 太复杂了?或者即使你只使用 complex 也会有陷阱吗?
      • 不再是,复杂的类可以追溯到早期的 c++,所以可能当时使用的任何推理现在都不再适用,(如果你死了,你可能会找到一些原始的讨论——开始知道)但没关系 - 绞尽脑汁也没用,我们就这样被他们困住了。
      • 这太不可思议了
      【解决方案3】:

      有关复杂运算符的概述,请参阅http://www.cplusplus.com/reference/std/complex/complex/operators/

      您会注意到 operator* 是一个模板,并将使用复杂类的模板参数来生成该代码。用于调用 operator* 的数字文字是 int 类型。使用comp = 3. * i;

      【讨论】:

        猜你喜欢
        • 2014-05-06
        • 2013-10-15
        • 1970-01-01
        • 2013-05-18
        • 2017-06-05
        • 2013-09-23
        • 2013-01-07
        • 1970-01-01
        • 2011-10-07
        相关资源
        最近更新 更多