从基类类型的向量访问派生类方法
Accessing derived class methods from a vector of type base class
在我的程序中,我有一个带有几个派生类的类。我试图在一个矢量存储派生类的所有实例。为此,vector具有基类类型,并且它们都存储在基类类型中。然而,当我试图访问一个方法,属于一个派生类从向量我不能这样做,因为基类没有这个方法。还有别的办法吗?示例代码如下:
#include <vector>
#include <iostream>
using namespace std;
class base
{
};
class derived
:public base
{
public:
void foo()
{
cout << "test";
}
};
int main()
{
vector<base*> *bar = new vector<base*>();
bar->push_back(new derived);
bar->push_back(new derived);
bar[0].foo();
}
使foo
成为base
类中的virtual
方法。然后在derived
类中重写它。
class base{
public:
virtual void foo()=0;
};
class derived
:public base
{
public:
void foo() overide
{
cout << "test";
}
};
现在可以用指向base
的指针/引用来调用foo
int main(){ // return type of main should be int, it is portable and standard
vector<base*> bar; // using raw pointer is error prone
bar.push_back(new derived);
bar.push_back(new derived);
bar[0]->foo();
return 0;
}
学习多态和虚函数
相关文章:
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 按基类对象访问派生类资源时出错
- C++11: 如何访问派生类中的基类成员?
- 访问派生类的 QMetaObject
- 使用基类对象访问派生的仅类方法
- 如何在 c++ 中通过基类引用访问派生类的对象?
- 如何在 c++ 中使用多态性访问派生类字段?
- C++继承从基类指针访问派生类中的非虚拟函数
- 无法访问派生类中的基类方法
- 如果基类指针无法访问派生类成员函数,那么多态性有什么方便的呢?
- 如果我们有一个基*类,如何访问派生模板类的成员函数
- 为什么我无法使用受保护/私有继承访问派生实例中基类的受保护成员?
- 通过在基类中虚拟调用派生类中的函数来访问派生类中的函数
- 无法访问派生类函数内的基类的受保护数据成员
- D 指针/pimpl 模式基类指针访问派生类成员
- 友元类对象是否可以在其成员函数中访问派生类对象的基类私有成员?
- 访问派生类C++中的受保护成员
- 从C++中的"interface"访问派生类成员?
- 通过基类的指针,我们无法访问派生类特定的成员
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++