在 C++11 中使用 cin 作为输入复数

gnh*_*nkz -2 complex-numbers c++11

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

int main(){
    complex<double> p;
    cin >> p.real() >> p.imag();
}
Run Code Online (Sandbox Code Playgroud)

在 g++4.7.2 中它成功运行,但在 C++11 中编译失败。为什么?

它给了我以下错误消息:

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

完整版:http : //ideone.com/M3BhVR

Bor*_*der 7

你可以像这样更简单地做到这一点:

cin >> p;
Run Code Online (Sandbox Code Playgroud)

格式必须是:(real,imag)(见:这里

或者您可以执行以下操作:

double real, imag;
cin >> real >> imag;
complex<double> p(real, imag);
Run Code Online (Sandbox Code Playgroud)