C ++:调用派生类的虚函数 [英] C++: Calling the virtual function of the derived class

查看:255
本文介绍了C ++:调用派生类的虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有虚函数的类和一个以不同方式实现虚函数的派生类。假设我还有一个用于存储派生类的基类向量。如何在不事先知道派生类是什么的情况下,在向量中执行派生类的虚函数?说明问题的最小代码:

Suppose I have a class with a virtual function and a derived class that implements the virtual function in a different way. Suppose I also have a vector of the base class used to store derived classes. How would I execute the virtual function of a derived class in the vector without knowing in advance what the derived class is? Minimal code that illustrates the problem:

#include <iostream>
#include <vector>

class Foo {
public:
    virtual void do_stuff (void) {
        std::cout << "Foo\n";
    }
};

class Bar: public Foo {
public:
    void do_stuff (void) {
        std::cout << "Bar\n";
    }
};

int main (void) {
    std::vector <Foo> foo_vector;
    Bar bar;

    foo_vector.resize (1);
    foo_vector [0] = bar;

    bar.do_stuff ();            /* prints Bar */
    foo_vector [0].do_stuff (); /* prints Foo; should print Bar */
    return 0;
}


推荐答案

你不能。向量中的对象将被切片 - 任何派生类实例数据都将被切断,因此调用该方法将是一个非常糟糕的主意。

You can't. The objects in the vector will have been sliced -- any derived-class instance data will have been chopped off, so calling the method would be a super-bad idea.

另一方面,如果你有一个指针的向量,那么你只需调用虚方法,并调用派生类版本。

If, on the other hand, you have a vector of pointers to base, then you simply call the virtual method, and the derived-class version will be invoked.

这篇关于C ++:调用派生类的虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆