1

我有一个用 C++ 编写大学的家庭作业。我有两个主要的抽象类学生和课程。在 Course 中,有不同的子类,例如 SoftwareEngineering 类...等 在 Student 中,有不同的子类,例如 SoftwareEngineering 学生类.. 等。

现在,在 Course 子类中,每个子类都有一个注册学生的功能

void register(Student &s);

当我调用每个课程子类(例如软件工程课程类)的函数寄存器时,我想将该学生引用推入向量中。但我得到了错误

 cannot allocate an object of abstract type 'Student'

Student 类是抽象的,并且有子类 SoftwareEngineeringStudent 等。但是我 - 必须 - 让注册函数获取一个抽象对象 Student,而不是像 SoftwareEngineeringStudent 这样的特定类型的学生。

有没有办法解决这个问题?

这是一个骨架(当然不是完整的代码!):

//Course.h
class Course{
virtual void reg(Student &s)=0

}
class SoftwareEngCourse : public Course{
void reg(Student &s);
}

//Student.h
class Student{
virtual void study(Course &c)=0;
}
class SoftwareEngStudent : public Student{
void study(Course &c);
}

现在在 Course.cpp 中:

//Course.cpp
void SoftwareEngCourse::reg(Student &s){
   vector_of_Student_object.push_back(s);
}
4

2 回答 2

5

In the comments you said that your vector is declared as:

std::vector<Student> vector_of_Student_object;

...and therein lies the problem. You trying to store Student objects in the vector, but you can't store a Student object because that class is abstract. Consider the following psudocode:

void foo(Student s)
{
}

int main()
{
  SoftwareStudent ss;
  foo(ss);
}

What happens to ss when foo is called? You are passing a SoftwareStudent, but foo just takes a Student. So ss is implicitly converted to its base class, Student which, since foo takes a Student by value, tries to construct a new Student by calling:

Student::Student(const Student& rhs)

In other words, the SoftwareStudent-specific attributes of ss You may not have implemented this constructor yourself, in which case the compiler did it for you.

The end result is you are trying to instantiate an abstract class because foo takes a Student by-value. This obviously won't work since you can't instantiate an abstract class.

This relates to your actual problem because your vector is a vector of Student objects, stored again by value. When you insert an object in to a vector, that object is copied. You end up trying to instantiate Student objects, which you can't do because Student is abstract.

You need to store something other than Student, either a Student reference or pointer. Since you can't have a vector of references, that leaves you with pointers.

Whenever dealing with pointers, it's best to deal with smart pointers rather than raw pointers as with smart pointers you don't need to worry as much about releasing the object, and very often you don't even have to use new explicitly. std::shared_ptr is probably the easiest to incorporate here, although std::unique_ptr might be a better fit semantically.

于 2012-11-13T14:37:59.387 回答
3

是的,vector_of_Student_object改为创建一个指向学生的(智能)指针向量。

无论如何,对象向量可能不是您想要的,因为对象将被切片

于 2012-11-13T13:57:40.967 回答