使用扩展类和派生类的方法

use the method of extended class and of derived

本文关键字:方法 派生 扩展      更新时间:2023-10-16

假设我有一个名为Foo的类和一个扩展Foo的名为Bar的类。我通过指针将它们存储在矢量中:

class Foo {
    void draw() {
        // stuff
    }   
};
class Bar() : public Foo {
    void draw() {
        // stuff
    }
}

vector<Foo*> someVector;
// put types of Foo and Bar in the vector
for (int i = 0; i < someVector.size(); i++) {
    Foo &f = someVector[i];
    // if it's of type bar it should
    // use that draw method
    f.draw();
}

现在它将始终使用Foo的绘制方法。但是,如果它是Bar类型的,我怎么能让它使用Bar的绘制方法呢?

编辑:多亏了Joe Z,我知道现在可以通过虚拟来实现这一点。但是如果它是"Bar"类型,而我想使用"Foo"的绘制方法呢?现在,对于虚拟,它总是选择"Bar"方法。

您需要使用virtual方法。这告诉编译器使用多态调度(即在运行时查找要调用的正确方法)。

class Foo {
    virtual void draw() {
        // stuff
    }   
};
class Bar : public Foo {
    virtual void draw() {
        // stuff
    }
};

这看起来像是一个合理的教程来解释这个概念:http://www.learncpp.com/cpp-tutorial/122-virtual-functions/