我正在进行一项任务,我们必须创建一个“学生”对象,其中“课程”成员数组是动态的,因此用户可以从一个课程进入数组中他们想要的数量。我一直在尝试这种方式,只是无法让数组调整大小并接受新元素。这是我现在的代码:
cout << "Enter student name > ";
cin >> name;
Student firstStudent(name);
cout << endl << "Enter \"done\" when you are complete";
cout << endl << "Enter a new course : ";
cin >> course;
while (course != "done") {
numCourses++;
firstStudent.addElement(numCourses, course);//makes the array bigger
cout << endl << "Enter a new course : ";
cin >> course;
}//end while
成员变量和构造函数:
class Student
{
private:
string name;//name of student
string *dynArray = new string[1];//array
public:
Student::Student(string name)
{
this->name = name;
this->numC = 1;//initialized to one to start with
}
调整大小并向元素添加元素:
void Student::addElement(int numCourses, string &course) {//DYNAMIC ARRAY
if (numCourses > this->numC) {//checks if there are more courses than there is room in the array
this->numC = numCourses; //this changes the member variable amount
dynArray[numCourses] = course;//adds new course to array
string *temp = new string[numC];//create bigger temp array
temp = dynArray;//write original to temp
delete[]dynArray; //this tells it that it's an array
dynArray = temp;//make dynarray point to temp
}
else {
dynArray[numCourses] = course;//adds new course to array
}
}//end addElement
即使我设法摆脱编译错误,它也常常会出现运行时错误。我确定它与指针/复制数组有关,但我只是在学习并且还没有掌握这些概念。
编辑:dynArray [numCourses] =课程;创建一个char数组。即如果course =“one”,dynArray [0] =“o”,dynArray [1] =“n”等等。有谁知道如何防止这种情况发生?
答案 0 :(得分:1)
看起来不太正确的第一行是这一行:
dynArray[numCourses] = course;
在检查numCurses > numC
之前,这意味着dynArray[numCourses]
访问内存越界(边界为0
到numC - 1
。
令我感到有趣的另一件事是addElement
方法将numCourses
作为参数。我希望它的行为应该与std::vector<T>::push_back
类似。你确定这个论点是必要的吗?
我想评论的最后一件事是不复制dynArray
的值。请查看std::copy_n
如何进行复制。
答案 1 :(得分:0)
我不确定这是否会被视为作弊,但这是对如何实施std :: vector的分解。您可以将其用作参考,然后选择您需要的部件。