【问题标题】:Calling and initializing static member function of class调用和初始化类的静态成员函数
【发布时间】:2021-01-28 22:07:54
【问题描述】:

我有以下代码:

#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))());
}

我可以在哪里正确初始化函数指针。但是我想让函数指针成为静态的,我想在这个类的所有对象中维护它的单个副本。 当我将其声明为静态时

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

我不确定将其初始化为函数 f 的方式/语法。任何资源都会有所帮助

【问题讨论】:

    标签: c++ class function-pointers member-function-pointers


    【解决方案1】:

    静态成员函数指针(我猜你已经知道这与指向静态成员函数的指针不同)是一种静态成员数据,所以你必须像你一样在类之外提供定义会处理其他静态成员数据。

    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))());
    }
    

    【讨论】:

    • 我不知道“使用”,比 typedef 更喜欢它。非常感谢您的回答
    • 在进行初始化时,我得到一个错误,“qualified name is not allowed”..我想知道这是否与编译器相关?
    • 好吧,我确实移动了“ptr_to_A_memfn A::x = &A::f;”在 main 里面,所以我猜我弄乱了命名空间
    • 静态数据成员的定义确实必须在命名空间范围内,而不是在任何函数中。静态数据成员从程序开始就存在。如果你喜欢,你可以在定义中做=nullptr,然后在main中使用普通的赋值语句赋值给&amp;A::f(修改现有的静态数据成员而不是定义一个新的)
    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多