复杂类的默认构造函数不起作用

时间:2018-03-21 11:15:35

标签: c++ most-vexing-parse

根据http://www.cplusplus.com/reference/complex/complex/complex/,类complex<double>有一个complex (double re = 0.0, double im = 0.0);形式的默认构造。但是,我不知道这是否真的正确。任何人都可以解释下面代码的奇怪行为吗?

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

int main() {

    complex<double> cmp1(1, 2);
    complex<double> cmp2(1); //isn't the same as cmp2(1, 0.0) ?
    complex<double> cmp3(); //isn't the same as cmp3(0.0, 0.0) ?

    cout << cmp1.real() << "\n"; //=> 1
    cout << cmp1.imag() << "\n"; //=> 2

    cout << cmp2.real() << "\n"; //=> 1
    cout << cmp2.imag() << "\n"; //=> 0

    //cout << cmp3.real() << "\n"; //error (why?) //mark1
    //cout << cmp3.imag() << "\n"; //error (why?)

    /* error message output by `mark1`: */
    /* request for member ‘real’ in ‘cmp3’, which is of */
    /* non-class type ‘std::complex<double>()’ */

    cout << cmp3 << "\n"; //=> 1 (why?)

    cout << typeid(cmp1).name() << "\n"; //=> St7complexIdE
    cout << typeid(cmp2).name() << "\n"; //=> St7complexIdE
    cout << typeid(cmp3).name() << "\n"; //=> FSt7complexIdEvE

}

环境:

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609

编译选项:

$ g++ -Wall -std=c++98 <file name>

1 个答案:

答案 0 :(得分:0)

变化:

complex<double> cmp3(); //isn't the same as cmp3(0.0, 0.0) ?

complex<double> cmp3; //isn't the same as cmp3(0.0, 0.0) ?

它应该可以正常工作

它发生了,因为编译器可能会认为这是一个函数声明