public 函数_UE4精品教程 | 渲染编程(C++篇)【第三卷:从仿函数到std::function再到虚幻4Delegate】...
本文轉(zhuǎn)載于YivanLee知乎作者
專題目錄鏈接:https://zhuanlan.zhihu.com/p/67694999
這幾天研究了一下虛幻4的delegate,但是想要理解這個,還得從仿函數(shù)說起。下面是一段代碼例子:
class MyFunctor{
public:
int operator()(int x) { return x * 2;}
}
MyFunctor doubler;
int x = doubler(5);
The real advantage is that a functor can hold state.
class Matcher{
int target;
public:
Matcher(int m) : target(m) {}
bool operator()(int x) { return x == target;}
}
Matcher Is5(5);
if (Is5(n)) // same as if (n == 5)
{ ....}
現(xiàn)在還可以使用std::function
#include#include
#include
using namespace std;
class MyCharacter
{
public:
void BeHurt01(int hurtvalue)
{
cout << "hurt01" << hurtvalue << endl;
}
void BeHurt02(int hurtvalue)
{
cout << "hurt02" << hurtvalue << endl;
}
};
class OtherCharacter
{
public:
functionThisIsDelegate;
};
int main()
{
MyCharacter mycha;
OtherCharacter othecha;
othecha.ThisIsDelegate = bind(&MyCharacter::BeHurt01, &mycha, placeholders::_1);
othecha.ThisIsDelegate(19);
return 0;
}
這樣做的好處就是實現(xiàn)延遲調(diào)用,比如我現(xiàn)在有個主角和一個怪物。因為需要完成動畫播放,主角的出招的特效播放之后才會執(zhí)行怪物受傷扣血的邏輯。這時候可以先在主角出招的時候探測周圍的怪物然后給他們綁定上傷害函數(shù)。
相對于函數(shù)指針,std::function能綁定c++里的所有可調(diào)用對象,stdfunction相當于幫我們封裝了一個模板。
比如:
(1)首先我們建立一個第三人稱c++模板工程
然后打開代碼,在MyProjectCharacter.h中聲明一個代理,兩個與之匹配的函數(shù)
在構(gòu)造函數(shù)中將函數(shù)和代理綁定
在MoveForward函數(shù)里執(zhí)行這個代理
完成綁定工作后我們到gamemode類里做如下工作
至此我們就可以在游戲執(zhí)行后,按下w鍵之后的log里看到如下的輸出
總結(jié)
以上是生活随笔為你收集整理的public 函数_UE4精品教程 | 渲染编程(C++篇)【第三卷:从仿函数到std::function再到虚幻4Delegate】...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3.5.2安装pygame_
- 下一篇: mysql 不能添加外键 1215_My