C Complex Numbers in C++?

前端 未结 3 1534
长情又很酷
长情又很酷 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 11:49

    Use the C keyword for complex: _Complex. C++ uses complex as a (template) class. I'm not sure where creal is or I would uncomment that.

    #include 
    #include 
    
    int main(int argc, char * argv[]) {
      double _Complex a = 3.0 + 0.0I;  // DECLARATION WORKS NOW - NOTE ASSIGNMENT MUST HAVE IMAG PART
      //printf("%lf\n", creal(a));
      return 0;
    }
    

    This works in gcc (I compiled with g++). I got a warning about deprecated .h headers.

    Here is a link to an email trail showing nonstandard compatibility with C++ and C with complex numbers. C++11 requires layout compatibility of C++ complexes with C _Complexes.

    I'm currently investigating creal, etc. in C++. I'm not finding anything in the standard. Since there seems to be some effort to provide some source compatibility between C++ and C then creal, cpow, etc. might make a nice addition to TR2 the library proposals.

提交回复
热议问题