C++裡,在類中使用指向類成員函數的指標

來源:互聯網
上載者:User
#include <stdio.h>class A{public://p1是一個指向非static成員函數的函數指標void (A::*p1)(void);//p2是一個指向static成員函數的函數指標void (*p2)(void);    A(){/*對**指向非static成員函數的指標**和**指向static成員函數的指標**的變數的賦值方式是一樣的,都是&ClassName::memberVariable形式**區別在於:**對p1隻能用非static成員函數賦值**對p2隻能用static成員函數賦值****再有,賦值時如果直接&memberVariable,則在VS中報“編譯器錯誤 C2276”**參見:http://msdn.microsoft.com/zh-cn/library/850cstw1.aspx*/p1 =&A::funa;p2 =&A::funb;//p1 =&A::funb;//error//p2 =&A::funa;//error//p1=&funa;//error,編譯器錯誤 C2276//p2=&funb;//error,編譯器錯誤 C2276    }    void funa(void){        puts("A");    }    static void funb(void){        puts("B");    }};int main(){    A a();//p是指向A中非static成員函數的函數指標    void (A::*p)(void);    p = a.p1;    (a.*p)();//列印A/*a.p2是指向static函數的函數指標,**儘管a.p2本身是個非static變數**所以下面這就話是錯的!*/    //p = a.p2;//error    return 0;}

參考資料:

1、C++類中函數指標賦值

2、編譯器錯誤 C2276

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.