You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++多线程调用其他类非静态成员函数报错求助

解决C++多线程调用非静态成员函数的错误:Invalid use of non-static member function

错误原因

非静态成员函数会隐式携带一个指向类实例的this指针作为第一个参数,直接把vm->helloFunction传给std::thread时,线程构造函数无法自动处理这个隐含的指针,因此触发错误。

解决方案

方法1:使用Lambda表达式(推荐)

Lambda可以直接捕获类实例,写法直观灵活,还能方便扩展逻辑:
修改main.cpp中的线程创建代码:

std::thread t1([vm]() {
    vm->helloFunction(20);
});
std::thread t2([vm]() {
    vm->helloFunction(30);
});

如果是栈上创建的VMGR实例(比如VMGR vm;),可以捕获引用避免拷贝:

VMGR vm;
std::thread t1([&vm]() {
    vm.helloFunction(20);
});

方法2:用std::bind绑定实例指针

std::bind可以把成员函数和类实例的this指针绑定成一个可调用对象,需要先包含<functional>头文件:

#include <functional> // 必须添加的头文件

// ...

std::thread t1(std::bind(&VMGR::helloFunction, vm, 20));
std::thread t2(std::bind(&VMGR::helloFunction, vm, 30));

参数顺序:成员函数地址 → 类实例指针/引用 → 成员函数的参数。

方法3:将成员函数改为静态函数(局限性大)

如果helloFunction不需要访问类的非静态成员,可以改成静态函数:
修改vmgr.h:

class VMGR{
public:
    static int helloFunction(int x); // 添加static关键字
};

vmgr.cpp的实现无需修改,之后main.cpp中可以直接创建线程:

std::thread t1(&VMGR::helloFunction, 20);
std::thread t2(&VMGR::helloFunction, 30);

注意:静态成员函数无法访问类的非静态成员,仅适合简单场景。

完整修正示例(Lambda版本)

#include <stdlib.h>
#include <iostream>
#include <thread>
#include <chrono>
#include <algorithm>
#include "vmgr.h"

using namespace std::chrono;

int main(int argc, char* argv[]) {

    VMGR *vm= new VMGR();

    std::thread t1([vm]() {
        vm->helloFunction(20);
    });
    std::thread t2([vm]() {
        vm->helloFunction(30);
    });

    t1.join();
    t2.join();

    delete vm; // 记得释放动态分配的内存
    return 0;
}

内容的提问来源于stack exchange,提问作者sarika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:24:31