c++ - C++ 方法没有被覆盖?

标签 c++ c++11 polymorphism overriding

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 类没有被覆盖?有一个 people 类, Instructor 和 Student 类继承了这些类。 People类中有一个虚方法,在Student和Instructor中实现。但它没有被覆盖?提前致谢!

最佳答案

您需要有指向对象的指针或引用才能进行覆盖工作:

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);
}

另外请考虑在你的基类中声明一个虚拟析构函数,如果你从 People 继承并在继承类中添加一个成员字段,那将是必须的:

class People {
    public:
        ...
        virtual ~People() {}
    protected:
        ...
}

关于c++ - C++ 方法没有被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666021/

相关文章:

sql - PostgreSQL 中的多态表

以元组作为模板参数的 C++ 可变参数模板

c++ - 在无法访问的语句中创建变量是否是明确定义的行为?

c++ - 右值引用可以绑定(bind)到函数吗?

java - 在java中传递后代而不是接口(interface)

java - Lejos (java) 和接口(interface)//UML 建议

c++ - 从基类调用指定方法

c++ - 编译器是否将普通的 getter 方法优化为简单的字段访问?

c++ - 如何在 Visual C++ 2008 Express Edition 中为我的程序设置图标?

c++ - 难忘的工厂 : When is constructor instantiated?