首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >指向成员函数的函数指针

指向成员函数的函数指针
EN

Stack Overflow用户
提问于 2010-03-08 23:54:04
回答 7查看 144.4K关注 0票数 106

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

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

代码语言:javascript
复制
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())
}

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

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-03-08 23:57:36

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

代码语言:javascript
复制
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中的指针。另一次将a作为左操作数添加到.*运算符将告诉编译器在哪个对象上调用函数。

票数 176
EN

Stack Overflow用户

发布于 2010-03-08 23:59:38

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

票数 29
EN

Stack Overflow用户

发布于 2016-05-28 22:39:34

Call member function on string command

代码语言:javascript
复制
#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)()声明函数指针的方法

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2402579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档