gpt4 book ai didi

c++ - 在 C++ 中将复数与常量相乘

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:08 24 4
gpt4 key购买 nike

以下代码编译失败

#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 有效。

最佳答案

第一行:

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>)

关于c++ - 在 C++ 中将复数与常量相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com