Different ways of constructing an object in C++

☆樱花仙子☆ 提交于 2019-12-20 10:36:59

问题


I want to construct an object in the stack, using C++. Do you know what is the difference between these to ways of calling the constructor (with and without parenthesis):

a) MyClass object ;

b) MyClass object() ;

I am using MFC and when constructing the global variable for the main app, if I use the latter way, I get an exception, I thought these two ways were equivalent.

Thank you guys for any information.


回答1:


This is one of those gotchas of C++.

MyClass object();

is the way that a function prototype is defined in C++, so the compiler thinks you are trying to declare another function in the middle of another function.

If you want to invoke the default constructor (i.e. the one which takes no arguments), use this syntax instead:

MyClass object;

See also Garth Gilmour's answer to the now-deleted question What is your (least) favorite syntax gotcha?:

In C++

Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype



回答2:


For example:

class MyClass
{
   public:
   MyClass()
   {x = 0;}
   MyClass(int X)
   {x = X;}
   private:
   int x;
};

int main()
{
   MyClass myObject(56); // initialize x to value '56'
   MyClass myObject2; //calls default constructor and initializes x to 0
   return 0;
}


来源:https://stackoverflow.com/questions/2308646/different-ways-of-constructing-an-object-in-c

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