[英]Is the constructor called immediately for an array of objects as a member of the class?
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? 我应该为g数组中的每个对象调用constuctor,还是会自动调用它?
eg, should I change the network class as follows: 例如,我应该如下更改网络类:
class network {
gene g[10];
network() {
for(int i = 0; i < 10; i++)
g[i] = gene();
}
}
In your case, because gene
has a non-trivial default constructor, each element of the array will be default-constructed for you. 在你的情况下,因为gene
有一个非平凡的默认构造函数,所以数组的每个元素都将默认为你构造。 Ie, 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. 如果您的数组的基本类型是POD类型的情况下,您将需要手动初始化的元素。 However, the way you're doing it is not ideal; 但是,你这样做的方式并不理想; you would want to use value-initialization instead: 你会想要使用值初始化 :
class network {
somePodType x[10];
public:
network() : x() { }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.