渔舟唱晚的天空
——welkinwalker的遐想

类的成员函数指针普通的函数指针 在C++中是完全两个不同的东西

今天偶然需要找了点资料才发现这个问题,写一个简单的例子 

 

#include <iostream>

using namespace std;

class test_class{
public:
    
void print(uint32_t num);
};

void test_class::print(uint32_t num){
    cout
<<num<<endl;
}


void print(uint32_t num){
    cout
<<num<<endl;
}

typedef 
void (test_class::*funptr)(uint32_t);

main()
{
    test_class a;
    funptr ptr
=&test_class::print;
    (a.
*ptr)(3);

} 

声明不一样, 普通情况使用(*fun_ptr)就行,这种情况要使用:

(类名::*funptr)

 

typedef void (test_class::*funptr)(uint32_t);

赋值的时候要注意,=右边是类名::函数名,而不是对象名::函数名 

funptr ptr=&test_class::print; 

调用的时候要注意,这个时候前面就要加上对象了,在这个例子里面可以用a.*,也可以用a-> 

(a.*ptr)(3); 

 

 参考了:http://blog.csdn.net/eroswang/article/details/4153356

 

贴出重要部分:

1。成员函数指针并不是普通的函数指针。

2。编译器提供了几个新的操作符来支持成员函数指针操作:

1) 操作符"::*"用来声明一个类成员函数指针,例如:
    typedef void (Base::*PVVBASEMEMFUNC)(void);        //Base is a class
2) 
操作符"->*"用来通过对象指针调用类成员函数指针,例如:
    //pBase is a Base pointer and well initialized
    //pVIBaseMemFunc is a member function pointer and well initialized

    (pBase->*pVIBaseMemFunc)();

3) 操作符".*"用来通过对象调用类成员函数指针,例如:
    
//baseObj is a Base object
    //pVIBaseMemFunc is a member function pointer and well initialized

    (baseObj.*pVIBaseMemFunc)(); 


3
。成员函数指针是强类型的。

    typedef void (Base::*PVVBASEMEMFUNC)(void);
    typedef 
void (Derived::*PVVDERIVEMEMFUNC)(void);
PVVBASEMEMFUNC
PVVDERIVEMEMFUNC是两个不同类型的成员函数指针类型。


4
。由于成员函数指针并不是真真意义上的指针,所以成员函数指针的转化就受限制。具体的转化细节依赖于不同的编译器,甚至是同一个编译器的不同版本。不过,处于同一个继承链中的不同类之间override的不同函数和虚函数还是可以转化的。

    void* pVoid = reinterpret_cast<void*>(pVIBaseMemFunc);            //error
    int*  pInt  = reinterpret_cast<int*>(pVIBaseMemFunc);             //error
  pVIDeriveMemFunc = static_cast<PVIDERIVEMEMFUNC>(pVIBaseMemFunc);   //OK

 

 

 

posted on 2011-08-22 16:34  welkinwalker  阅读(436)  评论(0编辑  收藏  举报