这里是 C++ 新手,这是我的第一篇文章。我正在学校做一个项目,但我有点卡住了。我的任务是创建一个课程名册。每个名册将包含课程名称、课程代码、课程学分和教授姓名。没问题,我有一个名册班。问题是我不确定如何使对象数组动态化,因为它必须能够在用户请求时增长和缩小。我一般对动态数组有些熟悉,但不确定对象动态数组的语法。而且,根据教授的指示,向量不是一种选择. 我搜索了这个论坛以及互联网上的其他区域,但没有找到答案,或者我不理解我找到的答案,并认为我会在这里发布。以下是我的非动态对象数组的代码。帮助转换为动态数组将不胜感激。谢谢!
StudentEnrollment.h:
#ifndef STUDENTENROLLMENT_H
#define STUDENTENROLLMENT_H
# include <iostream>
# include <string>
using namespace std;
class Roster {
private:
string courseName;
string courseCode;
string courseCredits;
string professorName;
public:
void setCourseName ( string );
void setCourseCode ( string );
void setCourseCredits ( string );
void setProfessorName ( string );
string getCourseName();
string getCourseCode();
string getCourseCredits();
string getProfessorName();
Roster ();
};
#endif;
StudentEnrollment.cpp:
#include <iostream>
#include <string>
#include "StudentEnrollment.h"
using namespace std;
// Roster class implementation
Roster::Roster () {
courseName = "";
courseCode = "";
courseCredits = "";
professorName = "";
}
void Roster::setCourseName ( string cn ) {
courseName = cn;
}
void Roster::setCourseCode ( string c ) {
courseCode = c;
}
void Roster::setCourseCredits ( string cc ) {
courseCredits = cc;
}
void Roster::setProfessorName ( string pn ) {
professorName = pn;
}
string Roster::getCourseName() {
return courseName;
}
string Roster::getCourseCode() {
return courseCode;
}
string Roster::getCourseCredits() {
return courseCredits;
}
string Roster::getProfessorName() {
return professorName;
}
主.cpp:
#include <iostream>
#include <string>
#include "StudentEnrollment.h"
using namespace std;
int main (int argc, char * const argv[]) {
int number_of_rosters = 0;
string course, code, credits, name;
cout << "Enter the number of rosters you would like to create: ";
cin >> number_of_rosters;
cin.ignore(100, '\n');
Roster roster[number_of_rosters];
for ( int i = 0; i < number_of_rosters; i++){
cout << "Enter course name: ";
getline(cin,course);
roster[i].setCourseName(course);
cout << "Enter course code; ";
getline(cin, code);
roster[i].setCourseCode(code);
cout << "Enter course credits: ";
getline(cin, credits);
roster[i].setCourseCredits(credits);
cout << "Enter professor name: ";
getline(cin, name);
roster[i].setProfessorName(name);
cout << "Next course..." << endl;
}
cout << endl;
for ( int i = 0; i < number_of_rosters; i++){
cout << roster[i].getCourseName() << endl;
cout << roster[i].getCourseCode() << endl;
cout << roster[i].getCourseCredits() << endl;
cout << roster[i].getProfessorName() << endl;
cout << endl;
}
return 0;
}
如果格式不正确,请原谅我。这是我的第一篇文章。
亚瑟