无法将函数指针转换为相同类型的另一个函数指针

时间:2017-07-20 15:57:48

标签: c++ function oop pointers

以下代码无法编译:

    #include <iostream>
    using namespace std;
    class A {
        int data;
        bool (*comparer)(int, int);
        bool defaultComparer(int x, int y) {
            return x == y;
        }
    public:
        A() {
            comparer = defaultComparer;
        }
        A(bool (*foo)(int, int)) {
            comparer = foo;
        }

    };
    bool myfunc(int a, int b) {
        return a == b;
    }
    int main()
    {
        A obj(myfunc);
    }

编译错误是:

11:12: error: cannot convert 'A::defaultComparer' from type 'bool (A::)(int, int)' to type 'bool (*)(int, int)'
   comparer = defaultComparer;
            ^

我的代码有什么问题?从comparer分配defaultComparer是错误的吗?如果是,那我该怎么办呢?

这与“Function pointer to member function”不同,因为我不想更改comparer的类型。

0 个答案:

没有答案
相关问题