C++虚函数

虚函数:多态性质,运行时编译

虚函数的实现:虚函数指针和虚函数表

虚函数指针 (virtual function pointer) 从本质上来说就只是一个指向函数的指针,与普通的指针并无区别。它指向用户所定义的虚函数,具体是在子类里的实现,当子类调用虚函数的时候,实际上是通过调用该虚函数指针从而找到接口。

虚函数指针是确实存在的数据类型,在一个被实例化的对象中,它总是被存放在该对象的地址首位,这种做法的目的是为了保证运行的快速性。与对象的成员不同,虚函数指针对外部是完全不可见的,除非通过直接访问地址的做法或者在DEBUG模式中,否则它是不可见的也不能被外界调用。

------文字转自博客https://blog.csdn.net/weixin_43329614/article/details/89103574

着重理解虚函数表,实例化的类对象共用一个虚函数表。空对象会有一个虚函数指针。另外,子类和父类的虚函数需一模一样,不然就只能算重载,子类并不能覆盖父类虚函数来实现多态。

侯捷《C++最佳编程实践》视频看讲解。

虚析构函数:只有当一个类被定义为基类的时候,才会把析构函数写成虚析构函数。保证基类指针被正确释放,不加virtual有内存泄漏风险。

 

在看AMCL时,用到虚函数,整理下

1、传感器类

// Base class for all AMCL sensors
class AMCLSensor
{
  // Default constructor
  public: AMCLSensor();
         
  // Default destructor
  public: virtual ~AMCLSensor();

  // Update the filter based on the action model.  Returns true if the filter
  // has been updated.
  public: virtual bool UpdateAction(pf_t *pf, AMCLSensorData *data);

  // Initialize the filter based on the sensor model.  Returns true if the
  // filter has been initialized.
  public: virtual bool InitSensor(pf_t *pf, AMCLSensorData *data);

  // Update the filter based on the sensor model.  Returns true if the
  // filter has been updated.
  public: virtual bool UpdateSensor(pf_t *pf, AMCLSensorData *data);

  // Flag is true if this is the action sensor
  public: bool is_action;

  // Action pose (action sensors only)
  public: pf_vector_t pose;

  // AMCL Base
  //protected: AdaptiveMCL & AMCL;

#ifdef INCLUDE_RTKGUI
  // Setup the GUI
  public: virtual void SetupGUI(rtk_canvas_t *canvas, rtk_fig_t *robot_fig);

  // Finalize the GUI
  public: virtual void ShutdownGUI(rtk_canvas_t *canvas, rtk_fig_t *robot_fig);

  // Draw sensor data
  public: virtual void UpdateGUI(rtk_canvas_t *canvas, rtk_fig_t *robot_fig, AMCLSensorData *data);
#endif
};

继承类有两个

class AMCLLaser : public AMCLSensor
class AMCLOdom : public AMCLSensor

 

2、传感器数据类

// Base class for all AMCL sensor measurements
class AMCLSensorData
{
  // Pointer to sensor that generated the data
  public: AMCLSensor *sensor;
          virtual ~AMCLSensorData() {}

  // Data timestamp
  public: double time;
};

 继承类也有两个

class AMCLLaserData : public AMCLSensorData
class AMCLOdomData : public AMCLSensorData

 

上一篇:【21天精听打卡 3/21】20211117 Is VR the new reality?


下一篇:c++虚函数反汇编特征