如何在使用for循环创建对象数组时将参数传递给构造函数


class Student
{
int rollNo;
string name;
public:
Student(int id_of_student, string name_of_student)
{
rollNo = id_of_student;
name = name_of_student;
}
void getStudentData()
{
cout<<"The name of the student with roll No. "<<rollNo<<" is "<<name<<endl;
}
};
int main()
{
Student *ptr = new Student[30]; // Error: no default constructor exists for class "Student"
return 0;
}

有没有什么方法可以将参数传递给构造函数?

Error: no default constructor exists for class "Student"

来自cppreference:

::(可选(new(placement_params((可选((type(initializer(可选(

如果初始值设定项是一个包含大括号的参数列表,则数组将进行聚合初始化。(自C++11起(

您可以使用可选的聚合初始值设定项,如下所示:

Student *ptr = new Student[3]{{1, "one"}, {2, "two"}, {3, "three"}};

然而,如果你有很多学生(比如你的例子中的30个(,那就不是很舒服了。

如果我是你,我会使用std::vector。然而,如果您更喜欢使用array,以下是我使用array(以及下面的std::vector示例(的方法

#include <iostream>
using namespace std;
class Student
{
int rollNo;
string name;
public:
Student(int id_of_student, string name_of_student)
{
rollNo = id_of_student;
name = name_of_student;
}
void getStudentData()
{
cout<<"The name of the student with roll No. "<<rollNo<<" is "<<name<<endl;
}
};
int main()
{
//Student *ptr = new Student[30]; // Error: no default constructor exists for class "Student"
Student *array[30];
//allocates 30 objects
for (int i = 0 ; i != 30 ; i++)
{
array[i] = new Student(i, "Name Array" + std::to_string(i));
}
//usage
for (int i = 0 ; i != 30 ; i++)
{
array[i]->getStudentData();
}
// freeing the 10 objects
for (int i = 0 ; i != 30 ; i++)
{
delete array[i];
}
// you may also use std::vector
std::vector<Student> arr;
//reserve for 30 objects
arr.reserve(30);
for (int i = 0 ; i != 30 ; i++)
{
arr.push_back( Student(i, "Name vector" + std::to_string(i))) ;
}
// usage
for (Student stu: arr)
{
stu.getStudentData();
}
}

一种简单的方法是使用std::vector

std::vector<Student> students;
//This is optional, it prevents multiple reallocations, which is nice
students.reserve(30);
students.emplace_back(id, name);
students.push_back(Student(id, name));

但是,您可以考虑只添加一个默认构造函数。对象是否已初始化将由您决定(我强烈建议不要添加像bool is_initialized这样的成员,以防您可能想要(

最新更新