2个问题:
roster[i]
时int i = 0
),循环只允许我将两个参数传递给我的构造函数。我知道这听起来很奇怪,但第一次循环调用与其他循环不同。#include<iostream>
#include<string>
using namespace std;
class Student{
public:
Student();
Student(string ln, string fn, string cn) {setLast(ln);setFirst(fn);setCourse(cn);}
void showInfo(){cout << firstname << " " << lastname << " in " << coursename << endl;}
protected:
void setLast (string l){lastname = l;}
void setFirst (string f){firstname = f;}
void setCourse (string c){coursename = c;}
string firstname;
string lastname;
string coursename;
};
int main(){
Student **roster;
int num;
cout << "how many?";
cin >> num;
roster = new Student*[num];
string l,f,c;
for (int i = 0; i < num; i++){
cout << "\nenter last, first, course: ";
getline(cin, l);
getline(cin, f);
getline(cin, c);
roster[i] = new Student(l, f, c);
roster[i]->showInfo();
}
delete [] roster;
};
答案 0 :(得分:0)
问题是你正在新建一个数组,并且你正在新建数组中的所有学生。您创建了new Student*[]
和一些new Student
,但只有delete[] arr
,您忘了delete x
在修复之前,我想建议您使用vector和unique_ptr,这样可以首先防止所有错误:
std::vector<std::unique_ptr<Student>> roster;
int num;
cout << "how many?";
cin >> num;
roster.reserve(num);
std::string l,f,c;
for (int i = 0; i < num; i++){
cout << "\nenter last, first, course: ";
getline(cin, l);
getline(cin, f);
getline(cin, c);
roster.emplace_back(std::make_unique<Student>(l, f, c));
roster.back()->showInfo();
}
现在,您的代码的解决方案。你应该把它放在代码的末尾:
for (int i = 0; i < num; i++){
delete roster[i];
}
delete [] roster;