如题,最近在研究如何用C++语言实现回调函数,写了一段代码,用来作简易说明。 结构如下
代码如下:
#include<iostream>
using namespace std;
class Sensor
{
public:
virtual void onSensorDataChanged(float sensorEvent)=0;
};
class SensorImpl
{
public:
SensorImpl(Sensor *_pSensor);
void onDataArrive(void);
private:
Sensor *pSensor;
};
SensorImpl::SensorImpl(Sensor *_pSensor)
{
this->pSensor = _pSensor;
};
void SensorImpl::onDataArrive(void)
{
float data = 112.33;
this->pSensor->onSensorDataChanged(data);
data = 555.89;
this->pSensor->onSensorDataChanged(data);
};
class SensorUser:public Sensor
{
public:
void onSensorDataChanged(float sensorEvent);
};
void SensorUser::onSensorDataChanged(float sensorEvent)
{
cout<<"now we show the sensor data on the screen:"<<endl;
cout<<sensorEvent<<endl;
};
int main()
{
SensorUser sensorUser;
SensorImpl sensorImpl(&sensorUser);
sensorImpl.onDataArrive();
system("pause");
};
运行效果如下:
|