C 方法没有被覆盖
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);
}
为什么do_work类没有被覆盖?有一个人班,讲师和学生班正在继承这些课程。人类班级中有一个虚拟方法,该方法在学生和讲师中实现。但是它没有被覆盖吗?预先感谢!
您需要对对象进行指示或引用以使工作:
Student* student1 = new Student("Don");
Instructor* instructor1 = new Instructor("Mike");
People* t = student1;
t->do_work(2);
,请不要忘记删除分配的内存:
delete student1;
delete instructor1;
这足以使其正常工作,但是为了安全起见和避免记忆泄漏,您可以走:
#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);
}
还请考虑在基础类中宣布虚拟破坏者,如果您从人继承并在继承的类中添加成员字段,那将是必须的:
class People {
public:
...
virtual ~People() {}
protected:
...
}
相关文章:
- 循环依赖,在继承类的情况下使用覆盖方法
- 确保模拟的 GTest 方法覆盖虚拟方法
- 覆盖作为另一个类的好友的虚拟受保护方法
- 如何使用方法覆盖在输出屏幕上显示堆栈整数值
- 是否有一种有效的方法来搜索队列中的关键字并覆盖其值
- 有没有办法仅在两个模板参数相同时才覆盖匹配的模板方法?
- C ++中的方法覆盖:是编译时还是运行时多态性?
- 错误"pure virtual method called",当此方法已被覆盖时
- 覆盖方法并用shared_ptr调用它们的奇怪行为
- 仅适用于某些模板类型的覆盖方法
- 在某些代码中覆盖方法的方式是什么?
- 为什么没有调用我的覆盖方法
- Poylmorphim,构造函数-C 中使用的覆盖方法
- 覆盖方法返回类型,在C 中使用不完整的派生类
- 从基类执行覆盖方法
- 如何自动化覆盖方法
- 在类模板上覆盖方法,编译器看不到它,只能看到其他重载函数
- 为什么不调用这个 Ruby 覆盖方法
- C++ 覆盖方法不起作用
- 代理dll:方法覆盖/方法转发(COM实现继承)