C++对象指针vector传入函数的实现方法咨询
问题根因
代码编译报错核心是类型不匹配:
- 你定义的
vector<StudentRecord>是存储StudentRecord值类型实例的容器 - 但
new StudentRecord(...)返回的是StudentRecord*堆指针类型,二者无法直接通过push_back传参 - 同时原有
displayStudents的参数类型、遍历访问逻辑也没有适配指针存储的场景,另外new创建的堆对象需要手动释放,否则会出现内存泄漏。
具体修改步骤
- 调整vector的存储类型,从值类型改为指针类型:将
vector<StudentRecord> students;修改为vector<StudentRecord*> students; - 重写
displayStudents函数,参数改为接收指针类型vector的引用,遍历访问时用指针成员运算符->调用display方法 - 修正原代码构造函数传参顺序错误:原构造函数接收姓名的参数顺序是
firstName在前、lastName在后,但CSV解析时先读的是lastName,原传参顺序会导致姓名字段存储颠倒 - 程序退出前遍历vector,逐个
delete释放new出来的堆对象,避免内存泄漏
修正后可运行代码
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> using namespace std; struct StudentRecord { public: StudentRecord( string id, string firstName, string lastName, int age, string phoneNumber, double gpa ) { Id = id; FirstName = firstName; LastName = lastName; PhoneNumber = phoneNumber; Age = age; Gpa = gpa; } void display() { cout << " Student ID: " << Id << endl; cout << " First Name: " << FirstName << endl; cout << " Last Name: " << LastName << endl; cout << " Phone Number: " << PhoneNumber << endl; cout << " Age: " << Age << endl; cout << " GPA: " << Gpa << endl; cout << endl; } string Id; string FirstName; string LastName; string PhoneNumber; int Age; double Gpa; }; // 修改为接收StudentRecord指针类型的vector引用 void displayStudents(vector<StudentRecord*>& students) { for (auto student : students) { // 指针类型用->访问成员方法 student->display(); } } int main() { ifstream inputFile; inputFile.open("TestFile.csv"); // 增加文件打开校验,避免文件不存在时程序崩溃 if (!inputFile.is_open()) { cerr << "Failed to open TestFile.csv" << endl; return 1; } string line = ""; // 修改vector存储类型为StudentRecord指针 vector<StudentRecord*> students; while (getline(inputFile, line)) { stringstream inputString(line); //StudentId, Last Name, FirstName, Age, Phone Number, GPA string studentId; string lastName; string firstName; int age; string phone; double gpa; string tempString; getline(inputString, studentId, ','); getline(inputString, lastName, ','); getline(inputString, firstName, ','); getline(inputString, tempString, ','); age = atoi(tempString.c_str()); getline(inputString, phone, ','); getline(inputString, tempString); gpa = atof(tempString.c_str()); // 修正传参顺序,匹配构造函数参数顺序 students.push_back(new StudentRecord(studentId, firstName, lastName, age, phone, gpa)); line = ""; } inputFile.close(); displayStudents(students); // 释放所有new创建的堆对象,避免内存泄漏 for (auto studentPtr : students) { delete studentPtr; } students.clear(); return 0; }
补充说明
- 以上写法仅为满足你练习
new运算符手动管理内存的需求,实际C++开发中更推荐使用std::unique_ptr/std::shared_ptr智能指针自动管理堆内存,不需要手动调用delete,可以从根源避免内存泄漏、重复释放等问题。
内容的提问来源于stack exchange,提问作者Alex S.
相关产品推荐
相关产品推荐

