在基类中调用派生类方法

时间:2014-07-15 06:12:35

标签: c++ class inheritance base derived

我们可以调用"基类方法"在派生类中。但是我们可以在基类函数中调用派生类方法吗?

#include<iostream.h>

class base {

 public:

   void print()
   {
     cout<<"base class";
   }

};

 class derived : public base

 {

  public:
    void print()
    {

            cout<<"derived class";

    }

 };

如何在Base类中调用此派生类print()函数?

3 个答案:

答案 0 :(得分:3)

您无法从基类调用派生类中定义的普通方法。你可以做的是在基类中添加一个virtual(可能是纯粹的)方法,在派生类中提供实现。您可以从base调用此方法。

class Base{
public:
 virtual void foo(){cout<<"Hello";};
 void bar() { foo();}
};

class Derived: public Base{
 public:
 void foo() override{ cout<<"Hi";}
};

int main() {
 Base* b1 = new Derived();
 b1->bar(); //will call Derived::foo()

 Base* b2=new Base();
 b2->bar(); // will call Base::foo()
}

答案 1 :(得分:2)

如果派生类对象是虚拟方法,则可以从基类方法调用派生类的方法:

class base {
  public:
    void doSomething() { 
      print();  
    }
    virtual void print() {
      cout<<"base class";
    }
};

class derived : public base {
  public:
    virtual void print() {
      cout<<"derived class";
    }
};

int main() {
  derived d;
  base* pb = &d;
  pb->doSomething();
}

它被称为Template method pattern

答案 2 :(得分:0)

如果您确定base的所有实例化都将作为derived的基类(可能是使用Curiously Recurring Template Pattern的情况),您可以简单地static_cast thisderived*

#include <iostream>

class base {
public:
    void call_derived_print();
    void print()
    {
        std::cout<<"base class";
    }
};

class derived : public base
{
public:
    void print()
    {
       std::cout<<"derived class";
    }
};

void base::call_derived_print() {
    //undefined behaviour unless the most-derived type of `*this`
    //is `derived` or is a subtype of `derived`.
    static_cast<derived*>(this)->print();
}