我在访问设置为指针数组的对象中的“ getDegreeProgram()”方法时遇到了麻烦;我所有的基类方法都可以使用,但是由于某种原因,我的子类方法甚至不可见。我怀疑我没有正确的语法,并将其所有子类对象转换为学生的基类。
roster.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 子类(它们是我的基本类“ student”的子类)
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(); };
答案 0 :(得分:1)
据我了解,您正在尝试访问classRosterArray
的元素并尝试调用getDegreeProgram()
。
对于此问题,请设置getDegreeProgram()
虚拟函数。
student.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;
。
答案 1 :(得分:0)
有两种解决方法。
您可以在此处通过将order by
函数虚拟化为基类select n.id, n.title
from (select n.*,
(@rn := if(@c = category_id, @rn + 1,
if(@c := category_id, 1, 1)
)
) as rn
from (select n.*
from news n
order by n.category_id, n.id desc, n.title
) n cross join
(select @rn := 0, @c := -1) params
) n
where n.rn <= 3;
并在派生类getDegreeProgram
,Student
中覆盖它来实现运行时多态。和securityStudent
。
networkStudent
这里的技巧是在编译时获取派生类的信息,并将基类的softwareStudent
指针类型转换为派生类的指针。 :-)
class Student {
...
public:
virtual int getDegreeProgram() = 0; // notice the virtual keyword and 0 at the end.
// 0 is for saying that it is pure virtual, meaning
// we don't have any definition for this function in
// this class. Such a class is also called as
// abstract class
...
}
class securityStudent : Student {
...
public:
int getDegreeProgram() override
{
// do the stuff you want to do
}
...
}
// driver stub
...
Student *student;
securityStudent sStudent;
networkStudent nStudent;
.
.
student = &sStudent;
student->getDegreeProgram(); // calls security student implementation of getDegreeProgram
student = &nStudent;
student->getDegreeProgram(); // calls network student implementation of getDegreeProgram
...