繁体   English   中英

传递对成员函数的引用

[英]Passing References to Member Functions

我一直在 C++ 中使用双线程 BST,我认为将我的访问者函数与我的各种遍历分开会很酷。 但是我不知道如何正确地将对成员函数的引用传递到我的遍历函数中。 这是我的问题的一个大大简化的版本:

class foo {
public:
    foo() {};
    ~foo() {};

    void print(int x) const { //visitor
        cout << x << endl;
    }

    void traverse(void (*visitor)(int)) { //traversal
        for (int i = 0; i < 9; i++)
            visitor(myAry[i]);
    }

    void printAll() { //function calling the traversal and passing it a reference to the visitor
        traverse(&print);
    }

    int myAry[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
};

问题当然出在traverse(&print); 陈述。

任何线索出了什么问题,或者我可以尝试不同的方法来达到相同的效果?

void (*visitor)(int)

在 C++ 中,这意味着:指向 function 的指针采用int参数并返回void

&print

此表达式的类型不是“指向 function 的指针,它采用int参数并返回void ”。 它是“指向class foo的方法的指针,该方法采用int参数并返回void ”。

Class 方法和函数不是一回事。 他们可能看起来一样,但事实并非如此。

在您的示例代码中,您不需要为print使用 class 方法,因此只需将其声明为static class 成员:

static void print(int x) const {
    cout << x << endl;
}

并且,在没有其他更改的情况下,这应该可以工作,因为它现在是 function。class 方法与 function 之间的区别在于 class 方法需要调用 object 的方法。

您的清晰代码可能确实需要指向 class 方法的指针。 在这种情况下, traverse()可能应该是这样的:

void traverse(void (*foo::visitor)(int)) {
    for (int i = 0; i < 9; i++)
        (this->*visitor)(myAry[i]);
}

这将被调用为

traverse(&foo::print);

这是因为void (*foo::visitor)(int)表示“指向class foo的方法的指针,该方法采用int参数并返回void ”。 这就是您的print

您必须指定 class 以及调用 function 的实例。 还要确保签名匹配。

void traverse(void(foo::*visitor)(int) const) {
//                 ^^^^^               ^^^^^
    for (int i = 0; i < 9; i++)
        (this->*visitor)(myAry[i]);
//       ^^^^^^
}

void printAll() {
    traverse(&foo::print);
//            ^^^^^
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM