是否立即为作为类成员的对象数组调用构造函数?
class gene{
int ind;
gene() {
ind = 0;
}
}
class network {
gene g[10];
}
main() {
network n;
}
我应该为 g 数组中的每个对象调用构造函数,还是会自动调用它?
例如,我应该按如下方式更改网络类:
class network {
gene g[10];
network() {
for(int i = 0; i < 10; i++)
g[i] = gene();
}
}
class gene{
int ind;
gene() {
ind = 0;
}
}
class network {
gene g[10];
}
main() {
network n;
}
Should I call the constuctor for each object in the g array, or it will be called automatically?
e.g, should I change the network class as follows:
class network {
gene g[10];
network() {
for(int i = 0; i < 10; i++)
g[i] = gene();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的情况下,由于
gene
有一个不平凡的默认构造函数,因此将为您默认构造数组的每个元素。即,不,您的更改是不必要的。如果数组的基础类型是 POD 类型,您将需要手动初始化元素。然而,你这样做的方式并不理想;您可能想使用值初始化来代替:
In your case, because
gene
has a non-trivial default constructor, each element of the array will be default-constructed for you. I.e., no, your change is unnecessary.In the circumstance that your array's underlying type is a POD type, you will need to initialize the elements manually. However, the way you're doing it is not ideal; you would want to use value-initialization instead: