Ade*_*que 5 c++ inheritance virtual-functions class vector
假设我有一个带有虚函数的类和一个以不同方式实现虚函数的派生类.假设我还有一个用于存储派生类的基类向量.如何在不事先知道派生类是什么的情况下,在向量中执行派生类的虚函数?说明问题的最小代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
Ern*_*ill 14
你不能.向量中的对象将被切片 - 任何派生类实例数据都将被切断,因此调用该方法将是一个非常糟糕的主意.
另一方面,如果你有一个指向 base 的指针向量,那么你只需调用虚方法,就可以调用派生类的版本.
| 归档时间: |
|
| 查看次数: |
2022 次 |
| 最近记录: |