0

我有这个小程序,我需要动态创建 Class 对象。请参阅下面的评论。

#include <conio.h>

#include "student.h"
#include "teacher.h"

int main() {
  short choose;

  do {

    std::cout << "\n1 - Insert student";
    std::cout << "\n2 - Insert teacher";
    std::cout << "\n3 - Show students";
    std::cout << "\n4 - Show teachers";
    std::cout << "\n5 - Exit";
    std::cout << "\n--> ";
    std::cin  >> choose;

    Student *students;

    switch (choose) {
    case 1 :
      // When user choose option 1, I would like to create
      // a new object "Student", so...
      students = new Student();
      // But if user choose 1 another time, how I create
      // another object "Student" ?
      // Could I do something like this?
      //  students = new Student[student_counter];
      break;
    }

  } while (choose != 5);

  system("pause");
  return 0;
}

学生类有一个构造函数。谢谢你。如果需要什么就告诉我。

4

1 回答 1

1

只需使用std::vector<Student>. 根本不需要动态分配:

std::vector<Student> students;

do {
  switch (choose) {
    case 1 :
      students.push_back(Student());
      break;
  }
}while(...)

如果您需要使用动态分配,因为它是分配的一部分,只需使用 astd::vector<Student*>students.push_back(new Student)。之后您必须手动释放内存。

于 2012-11-29T21:25:03.100 回答