问题描述
从我对全局范围的声明和定义的理解:
MyClass instance(); //声明函数返回一个MyClass
MyClass实例; //声明一个MyClass实例
声明一个变量并将其定义为在全局范围使用默认构造函数?
> Okay,因此 MyClass实例;
调用默认构造函数。任何人都可以解释这与此示例 a>:
int a; //未默认构造,将有随机数据
int b = int(); //将初始化为零
code> MyClass实例;
这是违反直觉的,因为要使用参数调用重载的构造函数,您将执行以下操作:
MyClass instance(param1,param2);
逻辑会告诉你传入一个空参数列表来调用默认构造函数,代码...
MyClass实例
...看起来像是编译器的原型而不是构造一个 MyClass
对象。
struct
和 class
在C ++中,除了默认情况下 struct
有 public
并且类
默认具有私人
成员。
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
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.
这篇关于如何使用C ++中的默认构造函数定义和声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!