【发布时间】:2021-07-03 07:08:49
【问题描述】:
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"
【问题讨论】:
-
为什么要使用
new而不是std::vector?对于后者,使用参数创建对象的问题稍微简单一些——你可以编写一个循环而不是很长的初始化列表。 -
在这种情况下,除了
emplace_back、new或 C++11 初始化方法之外,总是有旧的init-Function 选项。从构造函数中删除参数(或为它们提供默认值),但还要定义一个initfunction,它做同样的事情。然后您可以在分配对象后初始化对象。如果你愿意,即使在一个循环中。