c++ - C++ 中的 C 复数?

标签 c++ c99 complex-numbers

以下代码在 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 cv std::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 of z, and

reinterpret_cast<cv T(&)[2]>(z)[1] shall designate the imaginary part of z.

关于c++ - C++ 中的 C 复数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10540228/

相关文章:

c++ - 使用动态数组的简单地址簿

c - C 中带有 TI 编译器的结构中的可变长度数组(套接字编程)

c# - 我应该如何从字符串中获取复数?

c++ - C++11 中具有 C 链接的复杂类型

c++ - 二项分布压缩

c++ - 如何在 C++ 中禁用转义序列

c - 为什么在 stdbool.h 中使用整数而不是无符号整数?

c - C99 不支持函数重载有什么原因吗?

file-io - 读取文件 : "Bad repeat count" 时出现 Fortran 运行时错误

c++ - C++中的可变用户定义参数列表?