c++ - 将 C++ 函数指针分配给同一对象的成员函数

标签 c++ pointer-to-member this-pointer

如何让 test.calculate 中的函数指针赋值(可能还有其他)起作用?

#include <iostream>

class test {

    int a;
    int b;

    int add (){
        return a + b;
    }

    int multiply (){
        return a*b;
    }

    public:
    int calculate (char operatr, int operand1, int operand2){
        int (*opPtr)() = NULL;

        a = operand1;
        b = operand2;

        if (operatr == '+')
            opPtr = this.*add;
        if (operatr == '*')
            opPtr = this.*multiply;

        return opPtr();
    }
};

int main(){
    test t;
    std::cout << t.calculate ('+', 2, 3);
}

最佳答案

您的代码有几个问题。

首先,int (*opPtr)() = NULL; 不是指向成员函数的指针,而是指向自由函数的指针。像这样声明一个成员函数指针:

int (test::*opPtr)() = NULL;

其次,在成员函数的地址时需要指定类作用域,如下所示:

if (operatr == '+') opPtr = &test::add;
if (operatr == '*') opPtr = &test::multiply;

最后,通过成员函数指针调用,有特殊语法:

return (this->*opPtr)();

这是一个完整的工作示例:

#include <iostream>

class test {

    int a;
    int b;

    int add (){
        return a + b;
    }

    int multiply (){
        return a*b;
    }

    public:
    int calculate (char operatr, int operand1, int operand2){
        int (test::*opPtr)() = NULL;

        a = operand1;
        b = operand2;

        if (operatr == '+') opPtr = &test::add;
        if (operatr == '*') opPtr = &test::multiply;

        return (this->*opPtr)();
    }
};

int main(){
    test t;
    std::cout << t.calculate ('+', 2, 3);
}

关于c++ - 将 C++ 函数指针分配给同一对象的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864341/

相关文章:

c++ - 在 C++ 类中访问 C 风格的回调

c++ - 相同的 this 指针和可变参数类型的问题

c++11 - 返回 "this"作为右值

c++ - 一次更改的最短路径问题

c++ - 当从 DirectX BackBuffer 拉伸(stretch)到 WIndow 时,Windows 使用点采样

c++ - 将指针传递给非静态成员函数

c++ - "this"指针只是编译时的东西吗?

c++ - unique_ptr boost 等效?

c++ - 如何向编译器指示指针参数已对齐?

"events"和成员函数指针的 C++ 映射