C++ Strange constructor behaviour

2019-02-23 12:32发布

问题:

Can anybody explain to me the difference between Complex a; and Complex b();?

#include<iostream>

class Complex
{
public:

    Complex()
    {
        std::cout << "Complex Constructor 1" << std::endl;
    }

    Complex(float re, float im)
    {
        std::cout << "Complex Constructor 2" << std::endl;
    }

    ~Complex()
    {
        std::cout << "Complex Destructor" << std::endl;
    }    
};

int main()
{
    Complex a;
    std::cout << "--------------------------" << std::endl;
    Complex b();
    std::cout << "--------------------------" << std::endl;
    Complex c(0,0);
    std::cout << "--------------------------" << std::endl;

    return 0;
}

Output:

Complex Constructor 1
--------------------------
--------------------------
Complex Constructor 2
--------------------------
Complex Destructor
Complex Destructor

As you can see, Complex a; does call its default constructor, Complex b(); doesn't and Complex c(0,0); calls an overloaded constructor.

What is going on here? I thought, that Complex b(); would create a stack-variable and call it's default constructor to initialize it?

回答1:

Complex b(); is function declaration. That is function taking no arguments and returning Complex object.

This is very common mistake and has its own name: most vexing parse

C++11 helped with this issue by introducing uniform initialization syntax

Complex b{};


回答2:

Complex b(); declares a function that has no arguments and returns a Complex.