【问题标题】:How to obtain a pointer to member function? [duplicate]如何获得指向成员函数的指针? [复制]
【发布时间】:2015-11-17 17:11:32
【问题描述】:

我知道该问题将被标记为重复,因为我也阅读了一些关于 SO 的类似问题。但不幸的是,没有一个答案对我有用。我尝试了所有这些,最后我想问一下。

void AsyncClass::method1()
{
    cout << "method is called" << endl;
}

void AsyncClass::method2()
{
    auto t = new std::thread(this->method1);
}

这两种方法都是公共的和非静态的。这不会编译说

非标准语法;使用 '&' 创建指向成员的指针

还考虑了我尝试过的关于 SO 的答案

auto t = new std::thread(this->method1);
auto t = new std::thread(this->*method1);
auto t = new std::thread(&(this->method1));
auto t = new std::thread(&AsyncClass::method1);

它们都没有编译。正确的方法是什么?

【问题讨论】:

    标签: c++ member-function-pointers


    【解决方案1】:

    你应该这样做:

    auto t = new std::thread(&AsyncClass::method1, this);
    

    【讨论】:

    • 成功了。但为什么?如果 method1 带参数怎么办? this 会被视为参数吗?
    • this 本质上是(非静态)成员函数的隐藏的第一个参数。
    • 所有非静态方法都有隐式参数this(所以他们知道他们操作的是哪个实例),所有其他参数都在this之后
    • 是的,我已经尝试过了,它可以正常工作。我需要等待 4 分钟才能接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多