我有这个小程序,我需要动态创建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;
}
Student类有一个构造函数。 谢谢。如果需要什么,请告诉我。
答案 0 :(得分:1)
只需使用std::vector<Student>
即可。根本不需要动态分配:
std::vector<Student> students;
do {
switch (choose) {
case 1 :
students.push_back(Student());
break;
}
}while(...)
如果您需要使用动态分配,就像分配的一部分一样,只需使用std::vector<Student*>
和students.push_back(new Student)
即可。之后你必须手动释放内存。