1、函数变量
void print(string strName){ //函数A
cout << strName << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
function<void(string)> func = print; //<void(string)> 函数类型(参数类型)
func("A老师");
system("pause");
//输出结果:A老师
}
2、类的成员函数(绑定)
class CPeople{
public:
CPeople(const string& strName){
m_strName = strName;
}
void print(){
cout << m_strName << endl;
}
private:
string m_strName;
};
int _tmain(int argc, _TCHAR* argv[])
{
//function<void()> func = CPeople::print; //错误!类的普通成员函数必须通过对象来执行
CPeople* pPeople = new CPeople("A老师");
function<void()> func = CC_CALLBACK_0(CPeople::print, pPeople); //print()函数和pPeople绑定,再通过pPeople来执行
func();
system("pause");
return 0;
//输出结果:A老师
}
3、类的成员函数(绑定,额外携带参数)
class CPeople{
public:
CPeople(const string& strName){
m_strName = strName;
}
void print(string strBoyFriend1,string strBoyFriend2,int nNum){ //3个参数
cout << m_strName << endl;
cout << strBoyFriend1 << endl; //额外的参数
cout << strBoyFriend2 << endl;
cout << nNum << endl;
}
private:
string m_strName;
};
int _tmain(int argc, _TCHAR* argv[])
{
CPeople* pPeople = new CPeople("A老师");
function<void()> func = CC_CALLBACK_0(CPeople::print, pPeople,"男朋友1","男朋友2",5); //在绑定的时候传额外的参数
func();
system("pause");
return 0;
//输出结果:A老师 男朋友1 男朋友2 5
}
4、CC_CALLBACK_0 与 CC_CALLBACK_1 的区别
function<void(参数)> 有几个参数就 CC_CALLBACK_几
function<void()> func = CC_CALLBACK_0(CPeople::print, pPeople);
function<void(string)> func = CC_CALLBACK_1(CPeople::print, pPeople);
function<void(string,string)> func = CC_CALLBACK_2(CPeople::print, pPeople);
class CPeople{
public:
CPeople(const string& strName){
m_strName = strName;
}
void print(string strName,int nNum){ //占位符表示第一个位置被strName占用 传进来的5将放到额外的参数nNum中
cout << strName << endl;
cout << nNum << endl;
}
private:
string m_strName;
};
int _tmain(int argc, _TCHAR* argv[])
{
CPeople* pPeople = new CPeople("A老师");
function<void(string)> func = CC_CALLBACK_1(CPeople::print, pPeople, 5);
func("A老师"); //在调用执行函数的时候传参
func("王老师");
system("pause");
return 0;
//输出结果:A老师 王老师 5
}
5、类的静态成员函数(不需要绑定)
class CPeople{
public:
CPeople(const string& strName){
m_strName = strName;
}
static void printStatic(string strName) //静态成员函数
{
cout << strName << endl;
}
void print(string strName, int nNum){
cout << strName << endl;
cout << nNum << endl;
}
private:
string m_strName;
};
int _tmain(int argc, _TCHAR* argv[])
{
//CPeople* pPeople = new CPeople("A老师");
//function<void(string)> funStatic = CC_CALLBACK_1(CPeople::printStatic, pPeople); //错误,静态函数不需要绑定对象
function<void(string)> funStatic = CPeople::printStatic;
funStatic("A老师");
system("pause");
return 0;
//输出结果:A老师