Now, you are amazed and you may ask: what is reference to function? A reference to function is a function alias which repersent the function. Follow is a demo of reference to function.
template <class T1, class T2, class T3>
T1 sum(T2 p1, T3 p2) ...{
cout << "three parameters" << endl;
return p1 + p2;
}
int main()
...{
int (&pr)(char,int) = sum<int>; // fp is reference to function
cout << typeid(pr).name() << endl; // print: "int __cdecl(char,int)" in VS2008
}Ok!It is the time to see pointer to function and code is the best word in our world.
template <class T1, class T2, class T3>
T1 sum(T2 p1, T3 p2) ...{
cout << "three parameters" << endl;
return p1 + p2;
}
int main()
...{
int (*fp)(char,int) = &sum<int>; // fp is reference to function
cout << typeid(fp).name() << endl; // print: "int (__cdecl*)(char,int)" in VS2008
}
本文介绍了C++中函数引用和函数指针的概念,并通过示例代码展示了如何定义及使用函数引用与函数指针,帮助读者理解这两种机制的区别。
3208

被折叠的 条评论
为什么被折叠?



