Why is there no call to the constructor? [duplicate]

点点圈 提交于 2019-11-25 23:18:55

问题


This question already has an answer here:

  • Default constructor with empty brackets 9 answers

This code doesn\'t behave how I expect it to.

#include<iostream>
using namespace std;

class Class
{
    Class()
    {
        cout<<\"default constructor called\";
    }

    ~Class()
    {
        cout<<\"destrutor called\";
    }
};

int main()
{    
    Class object();
}

I expected the output \'default constructor called\', but I did not see anything as the output. What is the problem?


回答1:


Nope. Your line Class object(); Declared a function. What you want to write is Class object;

Try it out.

You may also be interested in the most vexing parse (as others have noted). A great example is in Effective STL Item 6 on page 33. (In 12th printing, September 2009.) Specifically the example at the top of page 35 is what you did, and it explains why the parser handles it as a function declaration.




回答2:


No call to constructor

Because the constructor never gets called actually.

Class object(); is interpreted as the declaration of a function object taking no argument and returning an object of Class [by value]

Try Class object;

EDIT:

As Mike noticed this is not exactly the same code as what you are feeding to the compiler. Is the constructor/destructor public or is Class a struct?

However google for C++ most vexing parse.




回答3:


You can use it like this:

Class obj;
//or
Class *obj = new Class(/*constructor arguments*/);


来源:https://stackoverflow.com/questions/3810570/why-is-there-no-call-to-the-constructor

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