-2
#include <iostream>
#include <complex>
using namespace std;

int main(){
    complex<double> p;
    cin >> p.real() >> p.imag();
}

In g++4.7.2 it works successfully, but in C++11 failed to compile. Why?

It gives me following error message:

prog.cpp: In function ‘int main()’:
prog.cpp:7:19: error: no match for ‘operator>>’ in ‘std::cin >> p.std::complex<double>::real()’

Full version: http://ideone.com/M3BhVR

a3f
  • 8,517
  • 1
  • 41
  • 46
gnhankz
  • 21
  • 1
  • 3

2 Answers2

7

You can do it even simpler like this:

cin >> p;

Format must be: (real,imag) (see: here)

Or you can do the following:

double real, imag;
cin >> real >> imag;
complex<double> p(real, imag);
Borgleader
  • 15,826
  • 5
  • 46
  • 62
  • 1
    gave you an alternative. the problem is you can't use the real() and imag() accessors because the return a copy and not a reference so you wouldn't actually be modifying the complex number but rather temporary doubles. – Borgleader Jul 17 '13 at 17:12
4

The problem is that p.real() and p.imag() do not return references, so they are temporary values and it doesn't make sense to write to temporaries.

Robert Mason
  • 3,949
  • 3
  • 31
  • 44
  • Which makes the "works successfully in gcc 4.7.2" a little suspect. I suspect the poster just meant "works without visible error" and didn't validate the complex value produced. – Andy Ross Jul 17 '13 at 16:54
  • i always use this notation to deal with space-separated value in C++. – gnhankz Jul 17 '13 at 17:11