kmiklas
kmiklas

Reputation: 13433

How to directly assign complex numbers to a variable?

Using the complex class and library, how do I assign a complex number to a variable?

I understand that I can set the value when I first instantiate the complex number.
I also understand that I can assign one instantiated complex number to another.
How can I directly assign a complex number to a variable?

Reference:
http://www.cplusplus.com/reference/complex/complex/operators/

Example:

#include <iostream>
#include <complex>

int main() {
    complex<double> a(1.2,3.4), b;
    cout << a; //-> (1.2,3.4)
    b = a;
    cout << b; //-> (1.2,3.4)
    b = (1.2,3.4);
    cout << b; //-> (3.4,0) <-- what the heck is this??
    return 0;
}

Upvotes: 9

Views: 12725

Answers (4)

songyuanyao
songyuanyao

Reputation: 172894

For (1.2,3.4), built-in comma operator will be called.

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing).

The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2. If E2 is a temporary, the result of the expression is that temporary. If E2 is a bit-field, the result is a bit-field.

It means 1.2 will be evaluated and then discarded, at last 3.4 is returned.

So b = (1.2,3.4); is equivalent to b = 3.4;, which will call std::complex::operator=(const T& x):

Assigns x to the real part of the complex number. Imaginary part is set to zero.

That's why you get the result of (3.4,0).

As @paddy suggested, you could solve the issue like:

b = {1.2,3.4};                 // copy-list-initialization (since c++11)
b = complex<double>(1.2, 3.4); // copy assignment via a temporary complex<double>
b = decltype(b)(1.2, 3.4);     // same as the above (since c++11)

Upvotes: 11

Christopher Oicles
Christopher Oicles

Reputation: 3107

I just wanted to get in on the act with this bad boy, compliments of C++14:

#include <iostream>
#include <complex>

int main() {
    using namespace std::literals;
    std::complex<double> b;
    b = 1.2 + 3.4i;
    std::cout << b << "\n";
}

Upvotes: 1

Jay
Jay

Reputation: 607

Try this, you can use b={1.2, 3.4} to assign a complex value

#include <complex>
#include <iostream>
using namespace std;
int main()
{
    complex<double> a = {1,2};
    complex<double> b;

    b = {1.2, 3.4};

    cout << a + b << "\n"; // (2.2,5.4)

}

Upvotes: 7

Lincoln Cheng
Lincoln Cheng

Reputation: 2303

The way you used your assignment operator = for the std::complex class only assigned the real part of the complex number.

So b = (1.2,3.4); is equivalent to changing the real part of b to 3.4 only.

To assign a complex number directly I think you can use b = complex<double>(1.2,3.4);

Upvotes: 4

Related Questions