class Student
{
private:
string name;
int year;
string semester;
int AmtClass;
static string Year[4];
public:
Student();
Student(int AmtClass);
Student(Student &);
void setName(string name);
void setYear(int year);
void setSemester(string semester);
void setAmtClass(int AmtClass);
string getName();
int getYear();
string getSemester();
int getAmtClass();
~Student()
{
if(AmtClass > 0)
delete [] course;
}
};
string Student::Year[4] = { "Freshman", "Sophomore", "Junior", "senior" };
Student::Student()
{
name = "";
year = 0;
semester = "";
AmtClass = 0;
}
Student::Student(int amount)
{
AmtClass = amount;
string *pName;
pName = new string[AmtClass];
for(int i = 0; i < AmtClass; i++)
{
pName[i] = "";
}
}
跳过Accessors和Mutator函数......
void readStudentData(Student &);
void printStudentData(Student);
int main()
{
int amount;
cout << "How many courses are you currently taking? ";
cin >> amount;
Student kid;
kid.setAmtClass(amount);
readStudentData(kid);
}
void readStudentData(Student &kid)
{
cin.ignore(10000, '\n');
int amount = kid.getAmtClass();
string name = "";
string semester = "";
int year = 0;
cout << "What is your full name? ";
getline(cin,name);
cout << "\nHow many years have you been in college? ";
cin >> year;
cout << "\nWhat is your current semester? ";
getline(cin,semester);
Student kid1(amount);
cout << "Please enter the name of all your courses." << endl;
for(int i = 0; i < amount; i++)
{
cout << "Course #" << i+1 << " : ";
getline(cin,pName[i]);
}
}
在实现我的pName是构造函数中的局部变量之后,好了编辑了这个程序......我应该创建一个构造函数,它接收一个与学生正在学习的课程数相对应的整数参数。函数动态分配字符串数组的课程,并将每个元素设置为“”。然后我应该用它来记录学生所选课程的名称。
答案 0 :(得分:0)
Year
数组应该只分配给amount
,就是这样:
Student::Student(int amount)
: Year(new std::string[amount]()), AmtClass(amount)
{
}
您也可以使用std::vector
,这样您就不必自己处理删除内存:
class Student
{
std::vector<std::string> Year;
// ...
};
Student::Student(int amount)
: Year(amount), AmtClass(Year.size())
{
}