c++ - 访问指针数组中的子类方法
问题描述
我一直无法访问设置为指针数组的对象中的“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(); };
解决方案
据我了解,您正在尝试访问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;
。
推荐阅读
- maven - 使用maven生成并执行JavaFX jar
- python - 泊松分布不适合计数数据?
- tensorflow - 如何在不使用估算器 API 运行训练/评估的情况下可视化 TensorFlow 图?
- oracle - 查找存储过程中的表列表
- java - 添加到 JList 时 JRadioButton 对齐无效
- python - 如何在 Python 中发布带有请求的链接
- amazon-s3 - aws s3api put-object 命令无法按预期工作
- redis - 如何理解 Redis Monitor 的输出?
- assembly - 标准化一个二补数
- docker - 如何在 Dockerfile 中为 Google Cloud 设置守护程序服务