首页 > 解决方案 > 访问指针数组中的子类方法

问题描述

我一直无法访问设置为指针数组的对象中的“getDegreeProgram()”方法;我所有的基类方法都在工作,但由于某种原因,我的子类方法甚至都不可见。我怀疑我没有正确的语法,并将我所有的子类对象转换为学生的基类。

名册.h:

   class roster { 
   private:   
   student** classRosterArray; //array of pointers

roster.cpp函数创建我的对象并将它们设置为指针数组


   void roster::createStudentObject() {
      classRosterArray = new student *[5]; //array of pointers
   if (degreeProgramInput == "NETWORK") {
      classRosterArray[rosterCounter] = new networkStudent();
   }
   else if (degreeProgramInput == "SECURITY") {
      classRosterArray[rosterCounter] = new securityStudent();
   }
   else classRosterArray[rosterCounter] = new softwareStudent();  
   }

有问题的student.h子类(它们是我的基类“学生”的子类)

    class networkStudent:public student {
    private: 
      int networkDegree;
    public:
      int getDegreeProgram();
      networkStudent();
    };
    class securityStudent:public student {
    private:
      int securityDegree;
    public:
      int getDegreeProgram();
      securityStudent();
    };
    class softwareStudent:public student {
    private:
      int softwareDegree;
    public:
      int getDegreeProgram();
      softwareStudent();
    };    

标签: c++c++11

解决方案


据我了解,您正在尝试访问classRosterArray并尝试调用getDegreeProgram().

针对这个问题,制作getDegreeProgram()虚函数。

学生.h

class student {
...

public:
    virtual int getDegreeProgram() = 0; // pure virtual function
};

学生的子类

class networkStudent:public student {
private: 
  int networkDegree;
public:
  virtual int getDegreeProgram();
  networkStudent();
};
class securityStudent:public student {
private:
  int securityDegree;
public:
  virtual int getDegreeProgram();
  securityStudent();
};
class softwareStudent:public student {
private:
  int softwareDegree;
public:
  virtual int getDegreeProgram();
  softwareStudent();
};

建议:

在这种情况下,因为getDegreeProgram()似乎是一个 getter 函数,我认为你应该将它声明为一个 const 函数。

编辑:

正如Richard所说,在 C++ 11 中,override为此目的为子类引入了关键字。所以,除了写作virtual int getDegreeProgram();,你也可以写作int getDegreeProgram() override;


推荐阅读