【问题标题】:Overriding virtual function not working, header files and c++ files覆盖虚函数不起作用,头文件和 C++ 文件
【发布时间】:2012-11-21 18:23:59
【问题描述】:

我们有一个名为 Student 的父类。我们有一个子类:StudentCS。

学生.h:

#include <iostream.h>
#include<string.h>
#include<vector.h>
#include "Course.h"
class Course;

class Student {
public:
    Student();
    Student(int id, std::string dep, std::string image,int elective);
    virtual ~Student();
    virtual void Study(Course &c) const;  // this is the function we have a problem with
    void setFailed(bool f);
[...]

};

学生.cpp:

#include "Student.h"

[...]

void  Student::Study(Course &c) const {

}

我们有 StudentCS.h:

#include "Student.h"
class StudentCS : public Student {
public:
StudentCS();
virtual ~StudentCS();
StudentCS (int id, std::string dep, std::string image,int elective);
void Study(Course &c) const;
void Print();
};

还有 StudentCS.cpp:

void StudentCS:: Study (Course &c) const{
    //25% to not handle the pressure!
    int r = rand()%  100 + 1;
cout << r << endl;
if (r<25) {
    cout << student_id << " quits course " << c.getName() << endl;
}

 }

我们主要创建学生:

Student *s;
vector <Student> uniStudent;
[...]
    if(dep == "CS")
        s = new  StudentCS(student_id,dep,img,elective_cs);
    else
        s = new StudentPG(student_id,dep,img,elective_pg);

    uniStudent.push_back(*s);

然后我们打电话去学习,但我们得到的是父母的学习,而不是孩子! 请帮忙!

代码可以编译,但在 uniStudent.Study() 上运行和调用时,它使用父级而不是子级

【问题讨论】:

  • 你会在你的程序中正常调用student虚函数吗?将 student 设置为抽象基类并将 study 设置为纯虚函数可能是个好主意。
  • student 中有我们将使用的函数。当我尝试通过执行以下操作使研究成为纯虚函数时: [Virtual void Study(Course &c) =0;] 并擦除 .cpp 文件中的植入,它没有编译。
  • 它没有确定编译,因为调用了父方法,这意味着虚拟调用不起作用,因此StudentCS 错过了它的vtable。
  • 您没有明确表示 StudentCS 是从 Student 派生的,尽管能够在不强制转换的情况下分配指针意味着它确实如此。我很想相信这段代码并不代表您的实际问题。
  • 现在编辑它以显示大部分 StudentCS.h ..

标签: c++ inheritance overriding virtual


【解决方案1】:

编辑:编辑后问题就清楚了。

问题在于您将基础具体对象存储在 STL 容器中。这会产生一个名为object slicing 的问题。

当您将学生添加到vector&lt;Student&gt; 时,由于向量的分配器建立在Student 类上,派生类的所有附加信息都将被丢弃。一旦将元素插入向量中,它们就会成为基本类型。

要解决您的问题,您应该使用vector&lt;Student*&gt; 并在其中直接存储对学生的引用。所以分配器只与指针相关,不会对你的对象进行切片。

vector<Student*> uniStudent;
...
uniStudent.push_back(s);
uniStudent[0]->study();

请注意,您可能希望使用smart pointer 以更强大的方式管理所有内容。

【讨论】:

  • 好的,我现在对其进行了一些编辑,以便更清楚地说明问题在于向量 uniStudent 我希望它的每个单元格都有不同类型的学生,并从该类型调用学习函数跨度>
  • 但是现在我该如何调用 uniStudent 的函数呢? uniStudent[0].study() 以前没有用吗? *uniStudent[0].study() 也不起作用??
  • 因为它们是指针,您需要使用正确的 (-&gt;) 运算符来访问对象的成员。
猜你喜欢
  • 1970-01-01
  • 2015-04-23
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2011-06-02
  • 1970-01-01
相关资源
最近更新 更多