1

There are different ways to represent complex number in C++.

  • suffix form: 1+2i
  • constructor form: complex<double>(1,2)

then I tried different ways to add complex number

#include <iostream>
#include <complex>

using namespace std;
typedef complex<double> cd;

int main()
{
    complex<double> a;
    a=1+2i+3+4i;  // working
    a=cd(1,2)+cd(3,4);  //working
    a=1+2i+cd(3,4);   //error
    cout<<a;
    return 0;
}

It outputs a lot of messages, and in the last line, it shows

mismatched types 'const std::complex<_Tp>' and '__complex__ int'
a=1+2i+cd(3,4);

What is wrong? Why can not add two different form of complex number?

JaMiT
  • 14,422
  • 4
  • 15
  • 31
user15964
  • 2,507
  • 2
  • 31
  • 57
  • 3
    Which toolset are you using? GCC does not like the integer constants. If I make them all doubles (`1.+2i+3.+4i`) etc it compiles. – 1201ProgramAlarm Sep 20 '20 at 02:40
  • @1201ProgramAlarm Hi. I use g++. But the problem is not `a=1+2i+3+4i;` I comment it as working. It is the line `a=1+2i+cd(3,4)` that is not working – user15964 Sep 20 '20 at 02:45
  • See the [notes here](https://en.cppreference.com/w/cpp/numeric/complex/operator_arith3#notes): "*Because template argument deduction does not consider implicit conversions, these operators cannot be used for mixed integer/complex arithmetic. In all cases, the scalar must have the same type as the underlying type of the complex number.*". In fact gcc [won't even compile](https://godbolt.org/z/Toxh8P) `a = 1 + 2i;` unless changed to `= 1.0 + 2i`. – dxiv Sep 20 '20 at 02:50
  • 1
    I tried several different versions of g++, and none of them accept `1+2i`. – aschepler Sep 20 '20 at 02:51
  • @dxiv that is wierd. I acutally not on linux. I use mingw on windows. 1+2i does work. g++ --version show 'g++ (x86_64-win32-seh-rev0, Built by MinGW-W64 project) 7.1.0' – user15964 Sep 20 '20 at 02:56
  • 1
    Looks `1+2i` might be accepted by gcc versions before 8 if the GNU extensions are turned on (e.g. `-std=gnu++14` instead of `-std=c++14`). – JaMiT Sep 20 '20 at 03:04
  • @JaMiT That hit the point. Indeed setting `-std=c++14` even `1+2i` is not compilable. Somehow, default `g++` can compile `1+2i` while can not compile `1+2i+cd(3,4)`. Change it to `1.+2i+cd(3,4)` all works. Thank you everyone. – user15964 Sep 20 '20 at 03:10
  • @user15964 Related [1](https://stackoverflow.com/questions/30656210/adding-doubles-and-complex-numbers-in-c), [2](https://stackoverflow.com/questions/1641819/why-is-complexdouble-int-not-defined-in-c), [3](https://stackoverflow.com/questions/47562514/simple-way-to-add-implicit-type-promotion-to-the-stdcomplex-class-operators). – dxiv Sep 20 '20 at 03:10

0 Answers0