回調函數的用法(類之間的通信)
來源:程序員人生 發布時間:2014-09-23 16:48:57 閱讀次數:2207次
// ConsoleApplication3.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;
//1 "方向盤" 類接收外部的操作, 把消息傳到 "車" 類中, 車類把消息傳入到 "輪子" 類上
//(子類發消息給父類)
//2 "方向盤" 類接收外部的操作, 把消息傳入到 "輪子" 類上
//(子類發消息給子類)
//方向盤類
class Steering
{
private:
function<void(float)> m_steeringAction;
public:
//設置回調函數
void setWheelConnectWithCar(function<void(float)> steeringAction)
{
m_steeringAction = steeringAction;
}
//轉動方向盤
void turn(float angle)
{
cout<<"Steering turn "<<angle<<" angle"<<endl;
m_steeringAction(angle);
}
};
//輪子類
class Wheel
{
public:
//轉動輪子方向
void turn(float angle)
{
cout<<"Wheel turn "<<angle<<" angle"<<endl;
}
};
//車類
class Car
{
public:
//雖然方向盤在車里, 但是用戶可以直接對它進行操作
Steering m_steering;
Wheel m_wheel;
Car()
{
setCarConnectWithWheel();
}
#if 1//1 "方向盤" 類接收外部的操作, 把消息傳到 "車" 類中, 車類把消息傳入到 "輪子" 類上
//設置車和方向盤連接的函數
void setCarConnectWithWheel()
{
std::function<void (float)> _fun = std::bind(&Car::steeringAction,this,std::placeholders::_1);
m_steering.setWheelConnectWithCar(_fun);
}
//當轉動方向盤時, 會調用該函數, 然后改函數讓輪子轉動相應的角度
void steeringAction(float angle)
{
m_wheel.turn(angle);
}
#else//2 "方向盤" 類接收外部的操作, 把消息傳入到 "輪子" 類上
//設置車和方向盤連接的函數
void setCarConnectWithWheel()
{
std::function<void (float)> _fun = std::bind(&Wheel::turn,&m_wheel,std::placeholders::_1);
m_steering.setWheelConnectWithCar(_fun);
}
#endif
};
int _tmain(int argc, _TCHAR* argv[])
{
Car _car;
//讓方向盤轉動30度
_car.m_steering.turn(30);
return 0;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈