#ifndef COURSE_H #define COURSE_H #include <string> using namespace std; class Course { public: Course(const string& courseName, int capacity); ~Course(); string getCourseName() const; void addStudent(const string& name); void dropStudent(const string& name); string* getStudents() const; int getNumberOfStudents() const; private: string courseName; string* students; int numberOfStudents; int capacity; }; #endif int main() { Course course1("Data Structures", 10); Course course2("Database Systems", 15); course1.addStudent("Peter Jones"); course1.addStudent("Brian Smith"); course1.addStudent("Anne Kennedy"); course2.addStudent("Peter Jones"); course2.addStudent("Steve Smith"); cout << "Number of students in course1: " << course1.getNumberOfStudents() << endl; string* students = course1.getStudents(); for (int i = 0; i < course1.getNumberOfStudents(); i++) cout << students[i] << ", "; cout << endl; cout << "Number of students in course2: " << course2.getNumberOfStudents() << endl; students = course2.getStudents(); for (int i = 0; i < course2.getNumberOfStudents(); i++) cout << students[i] << ", "; cout << endl; return 0; } #include <iostream> #include "Course.h" using namespace std; int main() { Course course1("C++", 10); Course course2(course1); course1.addStudent("Peter Pan"); course2.addStudent("Lisa Ma"); cout << "students in course1: " << course1.getStudents()[0] << endl; cout << "students in course2: " << course2.getStudents()[0] << endl; return 0; } 添加学生时,若数组容量不够,则创建一个更大的数组,并将内容拷贝到新的数组 编写测试程序,测试实现的类 |
|
看到你的帖子,就知道学期要结束了,又快放假了
|
|
参考stl vector的源码实现。
|
|
难过地up一下
|
|
,STL vector 内存分配策略指数递增。。。。。。。。
|
|
难过地up一下
|
|
初学者感到看不懂…… |
|
40分 |
类实现
class Course { public: Course(const string& courseName, int capacity); ~Course(); string getCourseName() const; void addStudent(const string& name); void dropStudent(const string& name); string* getStudents() const; int getNumberOfStudents() const; private: string courseName; string* students; int numberOfStudents; int capacity; }; Course::Course(const string& courseName, int capacity):courseName(courseName),capacity(capacity) { students = new string[capacity]; } Course::~Course() { delete[]students; students = nullptr; capacity = 0; numberOfStudents = 0; } string Course::getCourseName() const { return courseName; } void Course::addStudent(const string& name) { if (capacity == numberOfStudents) return; students[numberOfStudents++] = name; } void Course::dropStudent(const string& name) { int i, j; for (i = 0; i < numberOfStudents; i++) { if (students[i] == name) break; } if (i != numberOfStudents) //学生确实存在 { if (1 == numberOfStudents) { delete[]students; students = nullptr; numberOfStudents = 0; } numberOfStudents--; for (j = i; j < numberOfStudents; j++) students[j] = students[j + 1]; } } string* Course::getStudents() const { return students; } int Course::getNumberOfStudents() const { return numberOfStudents; } |