C++ 对函数的引用

53 阅读1分钟

优势:指针可以为空或无效。引用保证它有效且不为空(不存在空引用)

例:

#include <iostream>
using namespace std;

void doCall( void (&f)(int) )
{
    f( 42 );
}

void foo( int x )
{
    cout << "The answer might be " << x << "." << endl;
}

int main()
{
    doCall( foo );
}