以下代码在 C 中编译和运行得很好(至少根据 'gcc -std=gnu99'),但在 C++ 下编译失败,给出“第 5 行:错误:无法将 'double' 转换为 'double 复杂'在初始化中”。有人知道为什么吗?
#include "/usr/include/complex.h"
#include <stdio.h>
int main(int argc, char * argv[]) {
double complex a = 3; // ERROR ON THIS LINE
printf("%lf\n", creal(a));
return 0;
}
我意识到在 C++ 中还有另一种处理复数的方法,但我必须在 C++ 中使用 C 复数,因为这是给我的遗留代码的处理方式。如果您能提供帮助,谢谢!
最佳答案
C++ 编译器可以选择支持 _Complex
关键字作为扩展名(有一些是这样做的),但那是不可移植的。不幸的是,如果你想要一个可移植的 C++ 解决方案,你需要使用 C++ std::complex 模板。
好消息是 C++ std::complex numbers 保证与 C 复数兼容(在某种意义上,指向一个复数的指针总是可以转换为指向另一个的指针,正确的事情将会发生) ,这意味着如果您需要与需要 C 复数值的 C 库进行互操作,您将不会遇到任何麻烦。
C11:
Each complex type has the same representation and alignment requirements as an array type containing exactly two elements of the corresponding real type; the first element is equal to the real part, and the second element to the imaginary part, of the complex number.
C++11:
If
z
is an lvalue expression of type cvstd::complex<T>
then:— the expression
reinterpret_cast<cv T(&)[2]>(z)
shall be well-formed,—
reinterpret_cast<cv T(&)[2]>(z)[0]
shall designate the real part ofz
, and—
reinterpret_cast<cv T(&)[2]>(z)[1]
shall designate the imaginary part ofz
.
关于c++ - C++ 中的 C 复数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540228/