Re: [cpp] 请教, boost::none_t 中一个语法问题

Li Jie cpunion at gmail.com
Sun Apr 16 10:30:32 CST 2006


他列出的这个例子,是一个"指向成员变量的指针",它只保存成员变量的偏移,当然node_t本身是个类型,必须定义出实例。成员函数指针则函数地址,如果成员函数是虚函数,则保存相对于虚表的偏移。当然这只是实现上的不同,成员函数指针也可以说是成员指针,各种编译器的实现上可能不同。

简单的用法:

struct node_helper{
    int value1;
    int value2;
    void func1(){}
    void func2(){}
    virtual void func3(){}
};
typedef int node_helper::*node_t;
typedef void (node_helper::*FUNC)();

node_t node1 = &node_helper::value1;
node_t node2 = &node_helper::value2;
FUNC f1 = &node_helper::func1;
FUNC f2 = &node_helper::func2;
FUNC f3 = &node_helper::func3;

node_helper helper;
cout << helper.*node1 << endl; // 等价于cout << helper.value1 << endl;
cout << helper.*node2 << endl;
(helper.*f1)(); // 等价于helper.func1();

其它用法可以借鉴的有:《理解"指向成员的指针的不可逆性"》这篇文章,google一下就能找到。

这是一个不常用的特性,也是最难使用的一个特性之一,很多书都避免提到它。

2006/4/16, 张沈 鹏 (ZuRoc) <zsp747 at gmail.com>:
> copy from http://breakman.bokee.com/4476703.html
>
> (三)在C++类中使用函数指针。
> //形式3:typedef 返回类型(类名::*新类型)(参数表)
> class CA
> {
>  public:
>    char lcFun(int a){ return; }
> };
> CA ca;
> typedef char (CA::*PTRFUN)(int);
> PTRFUN pFun;
> void main()
> {
>    pFun = CA::lcFun;
>    ca.(*pFun)(2);
> }
>        在这里,指针的定义与使用都加上了"类限制"或"对象",用来指明指针指向的函数是那个类的这里的类对象也可以是使用new得到的。比如:
> CA *pca = new CA;
> pca->(*pFun)(2);
> delete pca;
>        而且这个类对象指针可以是类内部成员变量,你甚至可以使用this指针。比如:
>        类CA有成员变量PTRFUN m_pfun;
> void CA::lcFun2()
> {
>   (this->*m_pFun)(2);
> }
>        一句话,使用类成员函数指针必须有"->*"或".*"的调用。



More information about the Cpp mailing list