问题
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;
}
回答1:
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)
回答2:
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)
}
回答3:
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);
回答4:
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";
}
来源:https://stackoverflow.com/questions/36169567/how-to-directly-assign-complex-numbers-to-a-variable