Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用扩展类和派生类的方法_C++ - Fatal编程技术网

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

C++ 使用扩展类和派生类的方法,c++,C++,假设我有一个名为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 v

假设我有一个名为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的draw方法。但是如果它是Bar类型,我怎么能让它使用Bar的绘制方法呢

编辑: 多亏了Joe Z,我知道现在可以用virtual完成这项工作。但是如果它是'Bar'类型,而我想使用'Foo'的draw方法,该怎么办?现在使用虚拟方法时,它总是选择“Bar”方法。

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

class Foo {

    virtual void draw() {
        // stuff
    }   

};

class Bar : public Foo {

    virtual void draw() {
        // stuff
    }
};

这看起来是一个合理的教程,解释了这个概念:

谢谢,它很管用。但是如果它是Bar类型,并且我想使用Bar draw方法怎么办?调用->draw将分派到该类型的相应draw方法。假设您有Bar*x,那么x->draw将调用Bar::draw。也就是说,假设x指向一个它将指向的类Bar对象,除非您引入一个从Bar派生的新类,在这种情况下,x可以指向一个派生类。是否可以让x->draw调用Foo::draw?@clankill3r:不通过Bar*,因为Bar是一个派生类。但是Bar::draw的实现可以调用Foo::draw来完成一些工作(如果需要)。这就是x->draw调用Bar::draw,然后Bar::draw在内部调用Foo::draw。谢谢。我刚制定了一个方法。似乎是我的最佳解决方案。