C Complex Numbers in C++?

前端 未结 3 1530
长情又很酷
长情又很酷 2020-11-29 11:13

The following code compiles and runs just fine in C (at least according to \'gcc -std=gnu99\'), but it fails to compile under C++, giving \"line 5: error: cannot convert \'d

3条回答
  •  我在风中等你
    2020-11-29 12:08

    A C++ compiler could choose to support the _Complex keyword as an extension (and a few do), but that isn't portable. If you want to have a portable C++ solution, you need to use the C++ std::complex templates, unfortunately.

    The good news is that C++ std::complex numbers are guaranteed to be compatible with C complex numbers (in the sense that a pointer to one can always be converted to a pointer to the other, and the right thing will happen), which means that if you need to interoperate with a C library that expects C complex values, you won't have any trouble.

    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 then:

    — the expression reinterpret_cast(z) shall be well-formed,

    reinterpret_cast(z)[0] shall designate the real part of z, and

    reinterpret_cast(z)[1] shall designate the imaginary part of z.

提交回复
热议问题