C++如何用对象数组通过参数化构造录入学生信息并调用成员函数打印
可以实现该需求,你的代码存在以下问题:
- 类定义中没有实现
print()成员函数,调用不存在的成员函数必然会报错 - 对象数组定义在循环内部,每次循环都会重新创建一个仅包含1个元素的临时数组,合法下标只有0,你用
d[i]访问(i从1开始)属于数组越界,读取到的自然是内存垃圾值,甚至直接崩溃 - 若要存储10个学生的信息,需要在循环外部提前声明足够长度的存储容器,推荐使用
std::vector避免数组越界、默认构造缺失等问题
修改后可运行的代码如下:
#include<iostream> #include<string.h> #include<vector> using namespace std; class student { char name[10]; int id, rollno; public: student(char name[10], int id, int rollno) { strcpy(this->name, name); this->id = id; this->rollno = rollno; } // 新增打印成员函数 void print() { cout << "学生姓名:" << name << endl; cout << "学生学号:" << id << endl; cout << "学生编号:" << rollno << endl << endl; } }; int main() { const int STU_COUNT = 10; vector<student> stu_list; int id1, rollno1; char name1[10]; for(int i = 0; i < STU_COUNT; i++) { cout << "===== 录入第" << i+1 << "位学生信息 =====" << endl; cout << "输入学生姓名:"; cin >> name1; cout << "输入学生学号:"; cin >> id1; cout << "输入学生编号:"; cin >> rollno1; stu_list.emplace_back(name1, id1, rollno1); } // 批量打印所有学生信息 cout << "\n===== 所有学生信息如下 =====" << endl; for(int i = 0; i < stu_list.size(); i++) { cout << "第" << i+1 << "位学生:" << endl; stu_list[i].print(); } return 0; }
如果你一定要用原生对象数组实现,只需要给student类补充无参默认构造函数,再在循环中给每个数组成员赋值即可。
内容的提问来源于stack exchange,提问作者Anushk Pathak
相关产品推荐
相关产品推荐

