简体   繁体   English

从基类调用派生类c ++的函数

[英]calling the function of derived class c++ from base class

How i can call the function of derived class, without typecasting? 我如何在不进行类型转换的情况下调用派生类的功能?

base type: 基本类型:

class Fruit{
public: 
    virtual void show() {cout « "its a fruct" « endl;}
};

child: 儿童:

class Banana : public Fruit{
public: 
    void show() { cout « "it's yellow banana" « endl; }
};

array of derived pointers 派生指针数组

class Basket
{
  Fruit *fructs_; 
  //... 
public:
  void show();
  //...
};

void Basket:: show(){
  for(int i=0; i< index_; i++)
  (fructs_+i)->show(); // need call Banana::show here
}

C-style arrays cannot be used polymorphically because of complications with the sizes of the base and derived classes. 由于基类和派生类的大小复杂,因此不能多态使用C样式数组。 You should use a std::vector of Fruit smart pointers instead: 您应该使用Fruit 智能指针std::vector代替:

std::vector<std::shared_ptr<Fruit>> fruits;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM