函数指针

函数名跟数组名一样,都是地址。数组名是首元素的地址,函数名是函数入口处地址。比如一个函数名为 fun;

cout<<fun<<endl;   在VS翻译器下可以正确输出为地址,在GCC编译器下会输出为 1,只需要 cout<<(void *)fun<<endl; 即可。

#include <iostream>



using namespace std;



void print_x(int i)

{

    cout<<"x: "<<i<<endl;

}



void print_y(int i)

{

    cout<<"y: "<<i<<endl;

}



int main()

{

    cout<<"print_x:\t"<<(void *)print_x<<endl;



    typedef int size;

    size s = 3;

    cout<<"typeid(s).name():\t"<<typeid(s).name()<<endl;



    void (*f)(int);

    f = print_x;

    f(3);



    typedef void (*F)(int);

    F fx = print_x;

    fx(10);

    fx = print_y;

    fx(10);

}

 

#include <iostream>



  using namespace std;



  void hello()

  {

      cout<<"Hello"<<endl;

  }



  void run(void (*ptr_fun)())

  {

      (*ptr_fun)();

      (ptr_fun)();

  }



  int main()

  {

      run(hello);

  }

 

 

你可能感兴趣的:(函数指针)