构造函数/ OOP中的函数指针

时间:2018-07-30 03:33:43

标签: c++ function-pointers

我有两个班级:

typedef int(*sumpointer)(int a, int b);

class A 
{
    A(sumpointer a, int b, int c)
    {
        // DO SOMETHING
    }
};

class B {
    A *a;
    B()
    {
        a = new A(sum, 5, 6);
    }
    int sum(int a, int b) {
        return (a + b);
    }
};

在线a = new A(sum, 5, 6); 我有语法错误:

  

没有构造函数“ A :: A”的实例与参数列表参数匹配
  类型是(int(int a,int b),int,int)

我该如何解决?

2 个答案:

答案 0 :(得分:4)

您不能使用原始函数指针指向非静态类方法。您需要使用指向成员的指针,例如:

class A;

class B {
    A *a;
    B();
    int sum(int val1, int val2);
};

typedef int (B::*sumpointer)(int val1, int val2);

class A {
    A(B *b, sumpointer s, int val1, int val2);
};

A::A(B *b, sumpointer s, int val1, int val2)
{
    (b->*s)(val1, val2);
}

B::B() {
    a = new A(this, &B::sum, 5, 6);
}

int B::sum(int val1, int val2) {
    return (val1 + val2);
}

在C ++ 11和更高版本中,请改用std::function

#include <functional>

using sumpointer = std::function<int(int, int)>;

class A {
    A(sumpointer s, int val1, int val2);
};

class B {
    A *a;
    B();
    int sum(int val1, int val2);
};

A::A(sumpointer s, int val1, int val2)
{
    s(val1, val2);
}

B::B() {
    a = new A([this](int val1, int val2) { return this->sum(val1, val2); }, 5, 6);
    /* or:
    using std::placeholders::_1;
    using std::placeholders::_2;
    a = new A(std::bind(&B::sum, this, _1, _2), 5, 6);
    */
}

int B::sum(int val1, int val2) {
    return (val1 + val2);
}

答案 1 :(得分:1)

最简单的解决方法是将sumB中移出:

int sum(int a, int b) {
    return (a + b);
}

class B {
    A *a;
    B()
    {
        a = new A(sum, 5, 6);
    }    
};