这是一个必须使用动态创建的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;
}
答案 0 :(得分:1)
数组下标运算符返回数组的一个元素。
coursePTR[count]
相当于将指针递增到数组的开头并取消引用结果,例如:*(coursePTR + count)
。你得到的是Course
类型的对象(或对一个的引用)。所以你需要使用'dot'运算符,而不是'arrow'运算符来访问元素:
cin >> coursePTR[count].creditHours;
你还有另一个错误:
cin >> coursePTR[count].courseName >> endl;
^^^^
这不会编译。 endl
只能用于输出流。
答案 1 :(得分:0)
Course* readCourseArray(int &courses); // Update the definition to pass "courses" by reference.
Course* readCourseArray(int &courses) // Pass the courses by reference so that your main() has the value updated.
{
cout<<"\nHow many courses is the student taking?\n";
cin>>courses;
/*
You don't need this line.
*/
// const int *sizePTR = &courses;
/*
You've allocated space for "courses" no. of "Course" objects.
Since this is essentially an array of "Course" object, you
just have to use the "." notation to access them.
*/
Course *coursePTR = new Course[courses];
/*
"endl" cannot be used for input stream.
*/
for(int count = 0; count < courses; count++) //Enter course information
{
cout<<"\nEnter student "<<count<<"'s course name\n";
cin>>coursePTR[count].courseName;
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;
}
return coursePTR;
}