从基类类型的向量访问派生类方法

Accessing derived class methods from a vector of type base class

本文关键字:访问 派生 类方法 向量 基类 类型      更新时间:2023-10-16

在我的程序中,我有一个带有几个派生类的类。我试图在一个矢量存储派生类的所有实例。为此,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;
}

学习多态和虚函数