這是一個必須使用動態創建的Course數組完成的類指派。我正試圖讀取每個成員變量裏面的我的for循環,但我不知道如何去做。我用我的學生結構做了它,但是這是一個數組的差異讓我感到困惑,因爲我不知道如何繼續。讀入動態創建的指針數組結構數組
我的問題是在嘗試讀取struct成員時在readCourseArray
函數中。如果有人能告訴我我該怎麼做,我會很感激。我知道使用new
經營者不得與許多指針是不必要沿着理想,但它是我的教練是多麼需要分配中被打開。
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string firstName, lastName, aNumber;
double GPA;
};
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
Student* readStudent();
Course* readCourseArray(int);
int main()
{
int courses = 0;
Student *studentPTR = readStudent();
Course *coursePTR = readCourseArray(courses);
delete studentPTR;
delete coursePTR;
system ("pause");
return 0;
}
Student* readStudent()
{ Student* student = new Student;
cout<<"\nEnter students first name\n";
cin>>student->firstName;
cout<<"\nEnter students last name\n";
cin>>student->lastName;
cout<<"\nEnter students A-Number\n";
cin>>student->aNumber;
return student;
}
Course* readCourseArray(int courses)
{
cout<<"\nHow many courses is the student taking?\n";
cin>>courses;
const int *sizePTR = &courses;
Course *coursePTR = new Course[*sizePTR];
for(int count = 0; count < *sizePTR; count++) //Enter course information
{
cout<<"\nEnter student "<<count<<"'s course name\n";
cin>>coursePTR[count]->courseName>>endl;
cout<<"\nEnter student "<<count<<"'s course number\n";
cin>>coursePTR[count]->courseNumber;
cout<<"\nEnter student "<<count<<"'s credit hours\n";
cin>>coursePTR[count]->creditHours;
cout<<"\nEnter student "<<count<<"'s grade\n";
cin>>coursePTR[count]->grade>>endl;
}
return coursePTR;
}
你應該知道的一件直接的事情是,在返回指針的函數中,你不應該返回一個局部變量。當你在函數中創建一個指針時,當函數結束時它會超出範圍,當你嘗試使用現在已故的數據時會遇到問題。當你使用'cin'讀取變量時,'coursePTR [count]'被視爲一個普通變量,所以使用'。 operator'。你會使用'coursePTR'上的箭頭。 'coursePTR [count]'已經被解除引用,因爲'coursePTR [count]'被讀爲'*(coursePTR + count)' – chris 2012-02-22 23:30:21