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;
}
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)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With