简体   繁体   English

调用并初始化class的成员static function

[英]Calling and initializing static member function of class

I have the following code:我有以下代码:

#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>

class A {
public:
 int f();
 int (A::*x)();
};

int A::f() {
 return 1;
}

int main() {
 A a;
 a.x = &A::f;
 printf("%d\n",(a.*(a.x))());
}

Where I can initialize the function pointer correctly.我可以在哪里正确初始化 function 指针。 But I want to make the function pointer as static, I want to maintain single copy of this across all objects of this class. When I declare it as static但我想将 function 指针设为 static,我想在这个 class 的所有对象中维护这个的单个副本。当我将其声明为 static 时

class A {
public:
 int f();
 static int (A::*x)();
};

I am unsure of the way/syntax to initialize it to function f.我不确定将其初始化为 function f 的方式/语法。 Any resource would be helpful任何资源都会有所帮助

A static pointer-to-member-function (I guess you already know this is different from a pointer to a static member function) is a kind of static member data, so you have to provide a definition outside the class like you would do with other static member data.一个 static 指向成员函数的指针(我猜你已经知道这不同于指向 static 成员函数的指针)是一种 static 成员数据,所以你必须像你一样在 class 之外提供一个定义其他 static 会员资料。

class A
{
public:
   int f();
   static int (A::*x)();
};

// readable version
using ptr_to_A_memfn = int (A::*)(void);
ptr_to_A_memfn A::x = &A::f;

// single-line version
int (A::* A::x)(void) = &A::f;

int main()
{
   A a;
   printf("%d\n",(a.*(A::x))());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM