How do I make define and declare a variable using the default constructor in C++?

可紊 提交于 2019-12-23 22:39:33

问题


From my understanding of declarations and definitions, at the global scope:

MyClass instance();//Declares a function that returns a MyClass
MyClass instance;//Declares an instance of MyClass

Is it possible to declare a variable and define it to use the default constructor at global scope? What if I was using a structure instead of a class?

EDIT:

Okay, so MyClass instance; does call the default constructor. Can anyone explain how this is consistent with this example:

int a; // not default constructed, will have random data 
int b = int(); // will be initialised to zero

回答1:


MyClass instance;

will invoke the default constructor (i.e. the constructor with no parameters).

This is counter-intuitive, because to invoke an overloaded constructor with parameters you would do the following:

MyClass instance(param1, param2);

Logic would tell you that you pass in an empty argument list to invoke the default constructor, but the following code...

MyClass instance();

...looks like a prototype to the compiler rather than the construction of a MyClass object.

There is no difference between a struct and a class in C++, except that a struct has public members by default and a class has private members by default.




回答2:


  1. It doesn't matter whether you're at global scope or not.
  2. MyClass instance; is a definition (using the default constructor, not just a declaration. To get only a declaration (e.g. in a header file), you would use extern MyClass instance;.
  3. It doesn't matter, for this part, whether MyClass is a class or a struct. The only thing that changes between structs and classes in C++ is the default interpretation of whether members and bases are public or private.
  4. If you want to be explicit, you could write MyClass instance = MyClass();.



回答3:


MyClass instance;

is also a definition, using the default constructor. If you want to merely declare it you need

extern MyClass instance;

which is not a definition. Both, however, have external linkage.



来源:https://stackoverflow.com/questions/4424990/how-do-i-make-define-and-declare-a-variable-using-the-default-constructor-in-c

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