如何定义指向静态成员函数的函数指针? [英] How to define a function pointer pointing to a static member function?

查看:84
本文介绍了如何定义指向静态成员函数的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include "stdafx.h"

class Person;
typedef void (Person::*PPMF)();

// error C2159: more than one storage class specified
typedef static void (Person::*PPMF2)();  

class Person
{
public:
    static PPMF verificationFUnction()
    { 
        return &Person::verifyAddress; 
    }

    // error C2440: 'return' : cannot convert from 
    // 'void (__cdecl *)(void)' to 'PPMF2'
    PPMF2 verificationFUnction2()               
    { 
        return &Person::verifyAddress2; 
    }
private:
    void verifyAddress() {}

    static void verifyAddress2() {}
};

int _tmain(int argc, _TCHAR* argv[])
{
    Person scott;

    PPMF pmf = scott.verificationFUnction();
    (scott.*pmf)();
    return 0;
}

问题:我需要定义一个函数指针PPMF2来指向静态成员函数verifyAddress2.我该怎么办?

Question: I need to define a function pointer PPMF2 to pointing to a static member function verifyAddress2. How can I do it?

#include "stdafx.h"

class Person;
typedef void (Person::*PPMF)();
typedef void (Person::*PPMF2)();

class Person
{
public:
    static PPMF verificationFUnction()
    { 
        return &Person::verifyAddress; 
    }
    PPMF2 verificationFUnction2()
    { 
        return &Person::verifyAddress2; 
    }
private:
    void verifyAddress() {}

    static void verifyAddress2() {}
};

int _tmain(int argc, _TCHAR* argv[])
{
    Person scott;

    PPMF pmf = scott.verificationFUnction();
    (scott.*pmf)();

    return 0;
}

推荐答案

指向静态成员函数的指针只是普通的函数指针. typedef void(* PPMF2)().您可以像分配任何函数指针一样将其分配给静态成员函数,只是该静态成员函数位于类范围内:

A pointer to a static member function is just a normal function pointer. typedef void (*PPMF2)(). You assign it to a static member function like you assign any function pointer, only that the static member function is inside the class scope:

PPMF2 myfunc = &MyClass::StaticMemberFunc;

这篇关于如何定义指向静态成员函数的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆