首页 > 解决方案 > 如何从基类指针向量调用派生类函数?

问题描述

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

class A {
 private:
  int v1;

 public:
  void setv1(int v1) { this->v1 = v1; }
  int getv1() { return v1; }
  virtual void print() { cout << v1 << endl; }
};

class B : public A {
 private:
  int v2;

 public:
  void setv2(int v2) { this->v2 = v2; }
  int getv2() { return v2; }
  void print() {
    A::print();
    cout << v2 << endl;
  }
};

int main() {
  vector<A *> vect;
  B *b = new B();

  vect.push_back(b);

  vect.at(0)->setv2(5);
}

我目前正在学习继承。我想调用如图所示的 setv2 函数,但是当我这样做时,向量中的对象不再识别它。有没有办法让我拥有一个基类指针向量并允许其中的派生类调用它们的函数?

标签: c++inheritance

解决方案


推荐阅读