C ++:通过指针调用成员函数 [英] C++: Calling member function via pointer

查看:125
本文介绍了C ++:通过指针调用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个示例代码使用成员函数的指针,我想在运行时更改,但我不能使它的工作。我已经尝试过 this-> * _ currentPtr(4,5) (* this)._currentPtr(4,5)

I have this example code of using pointer to member function, which I want to change during runtime, but I cannot make it work. I've already tried this->*_currentPtr(4,5) (*this)._currentPtr(4, 5). What is the proper way of calling pointer to method inside same class ?

错误: 表达式必须有(指针到)函数类型

The error : expression must have (pointer-to-) function type

#include <iostream>
#include <cstdlib>

class A {

public:

    void setPtr(int v);
    void useFoo();

private:
    typedef int (A::*fooPtr)(int a, int b);

    fooPtr _currentPtr;

    int foo1(int a, int b);
    int foo2(int a, int b);
};

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = foo1;
    } else {
        _currentPtr = foo2;
    }
}

void A::useFoo(){

    //std::cout << this->*_currentPtr(4,5); // ERROR
}

int A::foo1(int a, int b){
    return a - b;
}

int A::foo2(int a, int b){
    return a + b;
}

int main(){

    A obj;

    obj.setPtr(1);
    obj.useFoo();

    return 0;
}


推荐答案

foo 的类来自(否则它认为它们是来自全局范围的函数):

You need to tell the compiler which class the foos are coming from (otherwise it thinks they're functions from global scope):

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = &A::foo1;
                  //  ^^^^
    } else {
        _currentPtr = &A::foo2;
                  //  ^^^^
    }
}

这里需要一组括号:

std::cout << (this->*_currentPtr)(4,5);
          // ^                  ^

这篇关于C ++:通过指针调用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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