当我声明一个数组时,所有变量/对象都会被声明。但是,如果对象的类有构造函数,会发生什么情况呢?我正在使用的类有 2 个构造函数 - 一个没有参数,另一个有几个参数。第一个构造函数会在声明后激活吗?或者没有构造函数会激活?
如果发生第一种情况,我将不得不创建一个函数来替换构造函数。
那么,新声明的数组中的对象会发生什么情况呢?
When I declare a an array, all the variables/objects get declared. But what happens with the objects, if their class has constructors? The class I'm using has 2 constructors - one with no arguments and one with a few arguments. Will the first constructor activate after the declaration? Or no constructors will activate?
If the first case happens, I'll have to make a function that replaces the constructors.
So, what happens with the objects in a newly declared array?
发布评论
评论(2)
这取决于您如何声明数组。成员将是默认、值或复制初始化的:
对于类类型,默认和值初始化会调用默认构造函数。复制初始化可以直接调用适当的构造函数。
如果您不想使用默认构造函数,则将无法使用大括号初始化程序并拼写出每个成员。
It depends how you declare the array. The members will be either default, value, or copy-initialized:
For class types, default- and value-initialization call the default constructor. Copy-initialization may call the appropriate constructor directly.
If you don't want to use the default-constructor, you won't get arround the brace-initializer and spelling out each member.
如果基础类型具有重要的默认构造函数,则数组将调用所有对象的默认构造函数。
我不太记得规则了,但是 int、char*、其成员都具有简单构造函数的结构等,都具有简单的默认构造函数。这些东西的数组(以及这些东西的数组的数组等)不会被初始化,除非你明确地这样做。
显式声明的默认构造函数绝不是微不足道的,因此数组中的 Foo 对象将被默认构造。
Arrays will invoke the default constructors on all objects if the underlying type has a non-trivial default constructor.
I don't remember the rules exactly, but ints, char*s, structs whose members all have trivial constructors, etc., all have trivial default constructors. Arrays of these things (and arrays of arrays of these things, etc.) won't be initialised unless you do so explicitly.
An explicitly declared default constructor is never trivial, so the Foo objects in your array will be default-constructed.