问题
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:
- It doesn't matter whether you're at global scope or not.
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 useextern MyClass instance;
.- 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. - 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