可以使用函数指针调用静态方法吗?如果是这样我们怎么称呼它? [英] Can a Static method be called using a function pointer? if so how can we call it?

查看:93
本文介绍了可以使用函数指针调用静态方法吗?如果是这样我们怎么称呼它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用函数指针调用静态方法

Calling a static method using a function pointer

推荐答案

这与使用任何方法的指针的方式相同,例如:

It is the same way you would use a pointer for any method, for example:
class CTest
{
    //
public:
    static int staticProc();
    static int staticTwo(int a, int b, char* psz);
};

// then in your main code, something like

    int (*pfun)() = CTest::staticProc; // pfun is the pointer to the static function
    int foo = pfun();  // call the function through the pointer



有时使用 typedef 会很有帮助:


Sometimes it can be helpful to use a typedef like:

typedef int		(*TFUN)(int a, int b, char* pc);
TFUN pfun = (TFUN)CTest::staticTwo;
int foo = pfun(1, 2, "foo");


静态方法与普通C函数完全一样,它们只是在命名空间内,如果函数可以某种方式获取指向类实例的指针,它们可以访问类的私有/受保护成员。另一个特点是你也可以使用静态方法的可见性,如果你把它放到保护或私有,那么它就不能从任何地方调用。
A static method works exactly like normal C functions, they are just inside a namespace and they have access to private/protected members of the class if the function can somehow get a pointer to the instance of the class. Another feature is that you can also play with the visibility of the static method, if you put it to protected or private then it can not be called from anywhere.


这篇关于可以使用函数指针调用静态方法吗?如果是这样我们怎么称呼它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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