回調(diào)函數(shù)的用法(類之間的通信)
來源:程序員人生 發(fā)布時(shí)間:2014-09-23 16:48:57 閱讀次數(shù):2213次
// ConsoleApplication3.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
//
#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;
//1 "方向盤" 類接收外部的操作, 把消息傳到 "車" 類中, 車類把消息傳入到 "輪子" 類上
//(子類發(fā)消息給父類)
//2 "方向盤" 類接收外部的操作, 把消息傳入到 "輪子" 類上
//(子類發(fā)消息給子類)
//方向盤類
class Steering
{
private:
function<void(float)> m_steeringAction;
public:
//設(shè)置回調(diào)函數(shù)
void setWheelConnectWithCar(function<void(float)> steeringAction)
{
m_steeringAction = steeringAction;
}
//轉(zhuǎn)動(dòng)方向盤
void turn(float angle)
{
cout<<"Steering turn "<<angle<<" angle"<<endl;
m_steeringAction(angle);
}
};
//輪子類
class Wheel
{
public:
//轉(zhuǎn)動(dòng)輪子方向
void turn(float angle)
{
cout<<"Wheel turn "<<angle<<" angle"<<endl;
}
};
//車類
class Car
{
public:
//雖然方向盤在車?yán)? 但是用戶可以直接對(duì)它進(jìn)行操作
Steering m_steering;
Wheel m_wheel;
Car()
{
setCarConnectWithWheel();
}
#if 1//1 "方向盤" 類接收外部的操作, 把消息傳到 "車" 類中, 車類把消息傳入到 "輪子" 類上
//設(shè)置車和方向盤連接的函數(shù)
void setCarConnectWithWheel()
{
std::function<void (float)> _fun = std::bind(&Car::steeringAction,this,std::placeholders::_1);
m_steering.setWheelConnectWithCar(_fun);
}
//當(dāng)轉(zhuǎn)動(dòng)方向盤時(shí), 會(huì)調(diào)用該函數(shù), 然后改函數(shù)讓輪子轉(zhuǎn)動(dòng)相應(yīng)的角度
void steeringAction(float angle)
{
m_wheel.turn(angle);
}
#else//2 "方向盤" 類接收外部的操作, 把消息傳入到 "輪子" 類上
//設(shè)置車和方向盤連接的函數(shù)
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;
//讓方向盤轉(zhuǎn)動(dòng)30度
_car.m_steering.turn(30);
return 0;
}
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)