【问题标题】:Accessing derived class methods from a vector of type base class [duplicate]从基类类型的向量访问派生类方法
【发布时间】:2014-05-25 15:58:19
【问题描述】:

在我的程序中,我有一个包含多个派生类的类。我正在尝试将派生类的所有实例存储在向量中。为此,向量具有基类类型,并且它们都存储在那里。但是,当我尝试从向量访问属于派生类的方法时,我不能这样做,因为基类没有此方法。有没有办法解决?示例代码如下。

#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();
}

【问题讨论】:

  • 这与vector 完全无关。您不能从基类指针调用派生类型的方法。你只能调用基类的方法。
  • 我们今天已经有this topic了?
  • 这是int main,而不是void main

标签: c++ inheritance vector


【解决方案1】:

base 类中创建foo 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;
}

了解polymorphismvirtual function

【讨论】:

    猜你喜欢
    • 2012-04-28
    • 2014-06-22
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多