gpt4 book ai didi

c++ - 错误 : cannot call member function 'void Fortest::run()' without object|

转载 作者:行者123 更新时间:2023-11-28 01:42:10 25 4
gpt4 key购买 nike

我正在编写一个非常简单的 C++ 程序。

#include<iostream>
#include<thread>

class Fortest{
private:
int x;
public:
Fortest(int a)
{
x=a;
}
void run(void)
{
cout<<"test sucesses!"<<endl;
}
};

int main()
{
Fortest hai(1);
std::thread t;

t=std::thread(std::ref(hai),&Fortest::run());
t.join();

cout<<"program ends"<<endl;
return 0;
}

而且我不断收到错误“无法调用没有对象的成员函数”。谁能帮我解决这个问题?

最佳答案

你有两个问题:

首先是您调用线程函数,传递一个指向它返回值的指针。您应该传递一个指向函数的指针。

第二个问题是你传递了 std::thread constructor参数顺序错误。指向函数的指针是第一个参数,调用它的对象是第二个(这是函数的第一个参数)。

即应该是这样的

t = std::thread(&Fortest::run, &hai);

关于c++ - 错误 : cannot call member function 'void Fortest::run()' without object|,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com