Multiplication of a complex with a constant in C ++

The following code cannot compile

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

with error: no match for 'operator * in' 3 * i What is wrong here, why can not I multiply with immediate constants? b * i work.

+4
source share
2 answers

In the first line:

 comp = b*i; 

Compiler call:

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

What is defined as:

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

In the second case, the corresponding int pattern does not exist, so the execution failed:

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

See http://www.cplusplus.com/reference/std/complex/complex/operators/ for an overview of complex operators.

You will notice that the * operator is a template and will use the template parameter of a complex class to generate this code. The number digit that you use to call the * operator is int. Use comp = 3. * i;

+4
source

Source: https://habr.com/ru/post/1307068/