c++ - 使用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"
解决方案
::(可选)新的(placement_params)(可选)(类型)初始化程序(可选)
如果初始化程序是用大括号括起来的参数列表,则数组是聚合初始化的。(C++11 起)
您可以像这样使用可选的聚合初始值设定项:
Student *ptr = new Student[3]{{1, "one"}, {2, "two"}, {3, "three"}};
但是,如果您有很多学生(例如您的示例中的 30 个),那就不太舒服了。
推荐阅读
- python - 提取熊猫中特定列名的值,如另一列中列出的那样
- r - 检查多个子字符串的文本
- android - getActiveNotifications 返回 null
- javascript - 如何在接收服务器响应时动态创建标签?
- java - 将数组列表内容添加到提供空文本的文本视图
- java - 多个弹跳点问题
- c++14 - C++中虚函数的意义
- c++ - 从源安装 gcc: bash: gcc -v /usr/bin/gcc: 是一个目录
- java - List 类型中的方法 add(? extends Customer)不适用于参数 (Customer)
- javascript - Angular 5 - 从请求中删除默认 HTTP 标头