在基类中调用派生类方法



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

#include<iostream.h>
class base {
 public:
   void print()
   {
     cout<<"base class";
   }
};
 class derived : public base
 {
  public:
    void print()
    {
            cout<<"derived class";
    }
 };

如何在基类中调用这个派生类print()函数?

不能从基类调用派生类中定义的普通方法。你所能做的是在基类中添加一个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()
}

可以在派生类对象的基类方法中调用派生类的方法,如果它是方法:

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

如果您确定base的所有实例化将作为derived的基类(可能是在使用好奇循环模板模式的情况下),您可以简单地将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();
}

相关内容

  • 没有找到相关文章

最新更新