How to initialize an array of objects in C++
There are two ways to initialize an array of objects in C++.
- Initialize the array elements using the default constructor: for constructors with no parameters, you can directly use curly braces initialization list. For example:
class MyClass {
public:
MyClass() {
// 默认构造函数
}
};
int main() {
MyClass array[5] = {}; // 初始化包含5个MyClass对象的数组
return 0;
}
- Initializing array elements using parameterized constructor: For constructors with parameters, you can initialize using braces initialization list and parameter list. For example:
class MyClass {
public:
MyClass(int value) {
// 带参数的构造函数
}
};
int main() {
MyClass array[5] = {1, 2, 3, 4, 5}; // 初始化包含5个MyClass对象的数组,每个对象使用不同的参数值
return 0;
}
When initializing a list using braces, if the number of elements is less than the size of the array, the uninitialized elements will be initialized using the default constructor.