[英]The C++ method is not getting overridden?
class People {
public:
People(string name);
void setName(string name);
string getName();
void setAge(int age);
int getAge();
virtual void do_work(int x);
void setScore(double score);
double getScore();
protected:
string name;
int age;
double score;
};
class Student: public People {
public:
Student(string name);
virtual void do_work(int x);
};
class Instructor: public People {
public:
Instructor(string name);
virtual void do_work(int x);
};
People::People(string name) {
this->name = name;
this->age = rand()%100;
}
void People::setName(string name) {
this->name = name;
}
string People::getName() {
return this->name;
}
void People::setAge(int age) {
this->age = age;
}
int People::getAge() {
return this->age;
}
void People::setScore(double score) {
this->score = score;
}
double People::getScore() {
return this->score;
}
void People::do_work(int x) {
}
Student::Student(string name):People(name){
this->score = 4 * ( (double)rand() / (double)RAND_MAX );
}
void Student::do_work(int x) {
srand(x);
int hours = rand()%13;
cout << getName() << " did " << hours << " hours of homework" << endl;
}
Instructor::Instructor(string name): People(name) {
this->score = 5 * ( (double)rand() / (double)RAND_MAX );
}
void Instructor::do_work(int x) {
srand(x);
int hours = rand()%13;
cout << "Instructor " << getName() << " graded papers for " << hours << " hours " << endl;
}
int main() {
Student student1("Don");
Instructor instructor1("Mike");
People t(student1);
t.do_work(2);
}
Why the do_work class is not getting overridden ? 为什么do_work类没有被覆盖? There is a people class and the Instructor and Student class are inheriting those classes.
有一个人类,讲师和学生班继承这些班级。 There is a virtual method in People class, which is implemented in Student and Instructor.
People类中有一个虚拟方法,它在Student和Instructor中实现。 But it is not getting overridden ?
但它没有被覆盖? Thanks in advance !
提前致谢 !
You need to have pointers or references to objects to make overriding work: 您需要有对象的指针或引用来进行重写工作:
Student* student1 = new Student("Don");
Instructor* instructor1 = new Instructor("Mike");
People* t = student1;
t->do_work(2);
And please don't forget to delete your allocated memory: 请不要忘记删除已分配的内存:
delete student1;
delete instructor1;
That would be just enough to make it work, but for the sake of safety and avoiding memory leaks, you can just go: 这足以让它工作,但为了安全起见并避免内存泄漏,你可以去:
#include <memory>
...
int main() {
auto student1 = std::make_unique<Student>("Don");
auto instructor1 = std::make_unique<Instructor>("Mike");
People* t = student1.get();
t->do_work(2);
}
Also please consider declaring a virtual destructor in your base class, that would be a must if you inherit from People and add a member field in the inherited class: 另外,请考虑在基类中声明一个虚拟析构函数,如果从People继承并在继承的类中添加成员字段,那将是必须的:
class People {
public:
...
virtual ~People() {}
protected:
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.