首页 > 解决方案 > 使用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"

标签: c++arraysclassobject

解决方案


cppreference

::(可选)新的(placement_params)(可选)(类型)初始化程序(可选)

如果初始化程序是用大括号括起来的参数列表,则数组是聚合初始化的。(C++11 起)

您可以像这样使用可选的聚合初始值设定项:

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

但是,如果您有很多学生(例如您的示例中的 30 个),那就不太舒服了。


推荐阅读