<address id="ousso"></address>
<form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
  1. C++函數指針學習教程

    時間:2025-11-09 20:55:51 C語言 我要投稿

    C++函數指針學習教程

      每一個函數都占用一段內存單元,它們有一個起始地址,指向函數入口地址的指針稱為函數指針。下面是小編分享的C++函數指針學習教程,一起來看一下吧。

    C++函數指針學習教程

      語法

      數據類型 (*指針變量名)(參數表):

      int (*myFunc)(double b, int c);

      說明

      函數指針的定義形式中的數據類型是指函數的返回值的類型。

      區分下面兩個語句:

      int (*p)(int a, int b);/pic/p>

      int *p(int a, int b);/pic/p>

      指向函數的指針變量不是固定指向哪一個函數的,而只是表示定義了一個這樣類型的變量,它是專門用來存放函數的入口地址的;在程序中把哪一個函數的地址賦給它,它就指向哪一個函數。

      在給函數指針變量賦值時,只需給出函數名,而不必給出參數。

      如函數max的原型為:int max(int x, int y); 指針p的定義為:int (*p)(int a, int b); 則p = max;的作用是將函數max的入口地址賦給指針變量p。這時,p就是指向函數max的指針變量,也就是p和max都指向函數的開頭。

      在一個程序中,指針變量p可以先后指向不同的函數,但一個函數不能賦給一個不一致的函數指針(即不能讓一個函數指針指向與其類型不一致的函數)。

      如有如下的函數:

      int fn1(int x, int y); int fn2(int x);

      定義如下的函數指針:

      int (*p1)(int a, int b); int (*p2)(int a);

      則

      p1 = fn1; /pic/p>

      p2 = fn2; /pic/p>

      p1 = fn2; /pic/p>

      定義了一個函數指針并讓它指向了一個函數后,對函數的調用可以通過函數名調用,也可以通過函數指針調用(即用指向函數的指針變量調用)。

      如語句:c = (*p)(a, b); /pic/p>

      函數指針只能指向函數的入口處,而不可能指向函數中間的某一條指令。不能用*(p+1)來表示函數的下一條指令。

      函數指針變量常用的用途之一是把指針作為參數傳遞到其他函數。

      函數指針使用舉例

      說明看代碼注釋就可以

      #include <iostream>

      using namespace std;

      class test

      {

      public:

      test()

      {

      cout<<"constructor"<<endl;

      }

      int fun1(int a, char c)

      {

      cout<<"this is fun1 call:"<<a<<" "<<c<<endl;

      return a;

      }

      void fun2(double d)const

      {

      cout<<"this is fun2 call:"<<d<<endl;

      }

      static double fun3(char buf[])

      {

      cout<<"this is fun3 call:"<<buf<<endl;

      return 3.14;

      }

      };

      int main()

      {

      /pic/p>

      double (*pstatic)(char buf[]) = NULL;/pic/p>

      pstatic = test::fun3; /pic/p>

      pstatic("myclaa");

      pstatic = &test::fun3;

      (*pstatic)("xyz");

      /pic/p>

      int (test::*pfun)(int, char) = NULL; /pic/p>

      pfun = &test::fun1; /pic/p>

      test mytest;

      (mytest.*pfun)(1, 'a'); /pic/p>

      /pic/p>

      void (test::*pconst)(double)const = NULL; /pic/p>

      pconst = &test::fun2;

      test mytest2;

      (mytest2.*pconst)(3.33);

      /pic/pic/p>

      /pic/p>

      /pic/p>

      /pic/p>

      /pic/p>

      return 0;

      }


    【C++函數指針學習教程】相關文章:

    c++函數指針使用示例02-09

    C語言指針函數和函數指針詳解12-08

    C++ this指針詳解08-28

    C語言中指針函數與函數指針有何區別02-28

    C語言學習中的指針用法教程12-10

    C語言函數指針變量07-25

    C語言的指針型函數02-20

    C語言函數的基本學習教程01-31

    C語言函數指針與回調函數詳解09-24

    • 相關推薦
    <address id="ousso"></address>
    <form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
    1. 日日做夜狠狠爱欧美黑人