提问者:小点点

指向成员函数的函数指针


我想设置一个函数指针作为类的成员,它是指向同一类中另一个函数的指针。 我这么做的原因很复杂。

在本例中,我希望输出为“1”

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

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


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

但在编译时失败。 为什么?


共3个答案

匿名用户

语法不对。 成员指针是与普通指针不同的类型类别。 成员指针必须与其类的对象一起使用:

class A {
public:
 int f();
 int (A::*x)(); // <- declare by saying what class it is a pointer to
};

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


int main() {
 A a;
 a.x = &A::f; // use the :: syntax
 printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}

a.x还没有说明要在什么对象上调用函数。 它只是说您希望使用存储在对象a中的指针。 在之前加上一个作为.*运算符的左操作数,将告诉编译器在什么对象上调用函数。

匿名用户

int(*x)()不是指向成员函数的指针。 成员函数的指针是这样写的:int(A::*x)(void)=&A::f;

匿名用户

对字符串命令调用成员函数

#include <iostream>
#include <string>


class A 
{
public: 
    void call();
private:
    void printH();
    void command(std::string a, std::string b, void (A::*func)());
};

void A::printH()
{
    std::cout<< "H\n";
}

void A::call()
{
    command("a","a", &A::printH);
}

void A::command(std::string a, std::string b, void (A::*func)())
{
    if(a == b)
    {
        (this->*func)();
    }
}

int main()
{
    A a;
    a.call();
    return 0;
}

注意(this->*func)();以及用类名void(A::*func)()声明函数指针的方法