非静态成员函数 int test::funcAB(int, int) 的无效使用

兰洛班

我在使用时遇到了一些问题 std::function

它适用于 static intfuncAB但实际上,我需要类中非静态的 std 函数。

#include <functional>
#include <iostream>

class test{   
    public:
    std::function<int (int, int)> func;
    int funcAB(int a, int b){
        return a + b;
    }
    test(){
        func = test::funcAB;
    }
};

int main(){
    using namespace std;
    test A;
    cout <<A.funcAB(10,11) << endl;
    cout <<A.func(11,12) << endl;
}

错误:

main.cpp:11:22: error: invalid use of non-static member function ‘int test::funcAB(int, int)’
         func = test::funcAB;
                      ^~~~~~
某程序员哥们

这里有两个问题:

首先是要获得指向成员函数的指针,您需要使用 address-of 运算符&&test::funcAB.

另一个问题是非静态成员函数需要调用一个对象。如果您没有对象,则无法调用它。

要解决第二个问题,请使用 std::bind

using namespace std::placeholders;  // for _1, _2, _3...
func = std::bind(&test::funcAB, this, _1, _2);

或者使用lambda

func = [this](int a, int b)
{
    return funcAB(a, b);
};

通常推荐使用 Lambda 超过std::bind.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

CC_SYNTHESIZE(int,beadColor,_BeadColor); 在非静态成员函数外部无效使用“ this”

如何设置 (*sa_handler)(int) 指向作为类成员的函数的指针?(非静态成员函数的无效使用)

使用函数从int *到int的无效转换

无效使用非静态成员函数

无效使用非静态成员函数C ++

Az 数据工厂:使用无效参数调用函数“int”

我可以对非静态类成员函数使用BOOST_TEST_CASE吗?

使用Google Test测试Map <int,vector>

在模板函数中从'const int *'到'int *'的无效转换

从int *到int的无效转换

线程错误:无效使用非静态成员函数

在头文件中无效使用非静态成员函数

Linux-信号:错误:无效使用非静态成员函数

C ++ freeRTOS任务,无效使用非静态成员函数

pthread_create-无效使用非静态成员函数

boost :: thread无效使用非静态成员函数

非静态成员函数c++线程linux的无效使用

错误:非静态成员函数 C++ 的无效使用

错误:在 C++ 中无效使用非静态成员函数

使用 base 10 Python 的 int() 的无效文字

将成员函数作为函数变量传递时,无效使用非静态成员函数C ++

带有std :: map <int,T>成员的类的不完整类型的无效使用

使用laravel 6在int上调用成员函数lastPage()

C ++:使用int vs struct静态依赖于静态成员变量的初始化

错误:int类型函数无效使用了void表达式

StringEnumConverter无效的int值

SQLiteDatabase上的int无效

无效使用非静态成员函数-类成员函数调用另一个类成员函数

为什么要使用int / int = int?