我有一个作业问题,要求:
从基类Student确定派生类GraduateStudent。它将添加一个名为Advisor的数据成员,以存储学生论文指导的名称。提供构造函数,析构函数,访问器和修饰符函数。该类将重写year函数,以使用完成的小时数返回两个字符串(“Masters”或“PhD”)之一,使用下表。
营业时间年
(大于)30博士
我写过:
using namespace std;
class Student
{
public:
Student( string s = "", int h = 0);
~Student();
string getName() const;
int getHours() const;
void setName(string s);
void setHours (int h);
string year () const;
private:
string name;
int hours;
};
class GraduateStudent: private Student
{
public:
GraduateStudent(string s = "", int h=0, string advisor=""); //constructor
~GraduateStudent(); //destructor
string getAdvisor();
void setAdvisor(string advisor);
//Class overrides??
private:
string Advisor;
}
给了类(class)学生,我添加了研究生派生的类(class)。
我的问题是,首先,如果我已经正确设置了派生类。我的第二个问题是如何在没有if语句的情况下覆盖year函数?我尝试使用这些语句,但是编辑器给了我错误,我怀疑这是一个 header 文件。
最佳答案
您“给定”的学生类(class)写得并不正确,无法正确覆盖年份功能。一般的用例场景(将学生对象保存在容器中将无法正常工作)。
因此,要修复(正确):
// Generally, poor practice to have a using namespace
// directive in a header file, instead just properly
// scope your variables (as below)
// using namespace std;
class Student
{
public:
Student( std::string s = "", int h = 0);
// Virtual desctructors allow you to properly free derived
// classes given a base class pointer
virtual ~Student();
std::string getName() const;
int getHours() const;
void setName(std::string s);
void setHours (int h);
// This function needs to be virtual to be overridable
virtual std::string year () const;
private:
std::string name;
int hours;
};
// Use Public inheritance, after all a
// GraduateStudent IS-A Student
class GraduateStudent: public Student
{
public:
GraduateStudent(std::string s = "", int h=0, string advisor=""); //constructor
~GraduateStudent(); //destructor
std::string getAdvisor();
void setAdvisor(string advisor);
//Class overrides??
// this function overrides the Student::year() function
std::string year() const;
private:
std::string Advisor;
}
另外,为什么您认为您需要不使用
year()
语句来实现if
函数?在这种情况下,这样做是适当的。关于c++ - C++中的派生类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7728737/