Ale
Ale

Reputation: 1199

Operations with complex numbers

I'd like to know how to perform some simple operations with complex numbers without using the real and the imaginary parts separately.

Example:

complex<double> A(0.0, 1.0);
complex<double> B;
B = A * 2 + A;

It doesn't compile:

error C2678: binary '*' : no operator found which takes a left-hand operand of type 'std::complex' (or there is no acceptable conversion)).

I read it's a problem of conversion. It's a real problem, especially in the case of more complex code.

Is there a way to do operations with complex numbers?

Upvotes: 2

Views: 2236

Answers (3)

Ahmed Masud
Ahmed Masud

Reputation: 22412

It is a conversion issue:

#include <iostream>
#include <complex>
using namespace std;

int main ()
{
  complex<double> A (5.0, 10.0);
  complex<double> B;

  B = A * 2.0 + A; 
  cout << "B = " << B << endl;
  return 0;
} 

works rather nicely.

Upvotes: 3

Mark Wilkins
Mark Wilkins

Reputation: 41252

It might be a conversion issue. Maybe specify the constant 2 as a floating point value:

B = A * 2.0 + A;

Upvotes: 3

Sufian Latif
Sufian Latif

Reputation: 13356

C++ provides operator overloading, which can be a very easy and friendly way to handle that.

Complex operator + (Complex a, Complex b)
{
    return Complex(a.real + b.real, a.imag + b.imag);
}

Complex operator * (Complex a, double b)
{
    return Complex(a.real * b, a.imag * b);
}

Upvotes: 2

Related Questions