C++ Strange constructor behaviour

我的未来我决定 提交于 2019-12-30 21:38:07

问题


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.



来源:https://stackoverflow.com/questions/13336283/c-strange-constructor-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!