类的成员函数指针

 

类的成员函数指针

 

1.在今天看到一个很奇怪的代码,更奇怪的时竟然可以编译通过!:

template<class AT, class BT>

int delay( int ms, BT * target = NULL )

{

    BT * tar;

    //只是指定一个指针,还没初始化

    void (BT::*fn)(int);

    //BT声明一个指针函数

    tar->*fn(0);

    //竟然可以直接调用!

    return 0;

}

 

2.反正就是不好理解呀,那就么自己试试啦!

#include<iostream>

using namespace std;

class C

{

    public:

        C(){}

        int ShowName(int);

};

 

int C::ShowName(int)

{

    cout<<"ShowName in class C!"<<endl;

}

 

我知道函数指针多用于作参数传递,那就写个调用函数

//如果参数写成int (*cfn)(int) 就变成普通函数指针而不是指定类C里的函数指针了

int invokeShowName( int (C::*cfn)(int)  )

{

//方法一,直接调用

    cnf(0);

 

//方法二,以指针方式

    C * p;

    (p->*cfn)(0);

}

 

3.调用方式(先注释 invokeShowName里的调用!)

(1) invokeShowName( C::ShowName );

报错: 对非静态成员函数 ‘int C::ShowName(int)’ 的使用无效

(2)    C * pc = new C();

 

    invokeShowName( pc->ShowName );

报错: 实参类型为 ‘int (C::)(int)’,与 ‘int (C::*)(int)’ 不匹配

 

(3) invokeShowName( &C::ShowName );

竟然OK!! 什么意思嘛, 竟然不通过对象就可以调用到类的非静态成员!!

 

4.  invokeShowName调用

(1) cnf(0)

报错: 必须用 ‘.*’ or ‘->*’ 调用 <cfn (...)’ 中的成员函数指针

 

(2)

    C * p;

      

    (p->*cfn)(0);

 

OK

 

6.来直接点吧!!竟然也可以!!~~~注意从头到尾都没有生成对象,只是有个类指针,按理说应该是没有分配到空间呀,不过当然,类的成员函数已经绑定,就是说函数地址是确定有的,没有对象只是没有复制到用户的栈/堆空间里!

 

    int (C::*ppfn)(int) = &C::ShowName;

    C * p; //只有指针没有对象

    (p->*ppfn)(0);

 

6.完整程序

  1. #include<iostream>
  2. using namespace std;
  3. class C
  4. {
  5.     public:
  6.         C(){}
  7.         int ShowName(int);
  8. };
  9. int C::ShowName(int)
  10. {
  11.     cout<<"ShowName in class C!"<<endl;
  12. }
  13. int invokeShowName( int (C::*cfn)(int)  )
  14. {
  15.     C * p;
  16.     (p->*cfn)(0);
  17. }
  18. template<class AT, class BT>
  19. int delay( int ms, BT * target = NULL )
  20. {
  21.     BT * tar;
  22.     void (BT::*fn)(int);
  23.     tar->*fn(0);
  24.     return 0;
  25. }
  26. int main()
  27. {
  28.     //invokeShowName( C::ShowName );
  29.     //invokeShowName( pc->ShowName );
  30.     invokeShowName( &C::ShowName );
  31.     int (C::*ppfn)(int) = &C::ShowName;
  32.     C * p;
  33.     (p->*ppfn)(0);
  34.     return 0;
  35. }

 

 

 

原来这个是C++里的成员函数提针,呵算是又加深了对C++的理解,详细的分析可以看:

http://topic.youkuaiyun.com/u/20071011/10/D8693A60-B279-4794-AA0A-1E98731DFF79.html

http://dozb.bokee.com/1783751.html

 

测试环境:

ubuntu 7.04( 2.6.20 .17)

gcc 版本 4.1.2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值