最近我开始使用 boost::thread(也尝试使用 STL - thread)来建立聊天。 我在我的“服务器站”做了一个类
- void 从 main.cpp 获取调用的函数,启动服务器监听 + 绑定(bind)
- void 函数,即从我之前声明的函数调用的线程
代码:
this is ServerSocket.cpp file
void ServerSocket::startHosting()
{
Bind();
Listen();
boost::thread clients_listener = boost::thread(&ServerSocket::clientsListener);
}
//This is the thread function
void ServerSocket::clientsListener()
{
..... handling incoming clients sockets , code goes here ....
}
在创建线程部分,我添加了“this”,因为我在 stackoverflow 上读到,非静态成员函数必须具有代表该类的“this”成员,但是当我添加时,我又遇到了另一个错误,但这次是 1未给出“this”时的值而不是 0
错误 C2064 - 项未计算为采用 1 个参数的函数
有人知道如何解决这个问题并向我解释一下答案吗? 我可以做一个静态函数,但这需要我将该函数中需要的所有其他成员设为静态,但我不想这样做
最佳答案
在下一行中:
boost::thread clients_listener = boost::thread(&ServerSocket::clientsListener);
您传递了成员函数指针,但缺少应用指针的对象。你可能想要这样的东西:
boost::thread clients_listener = boost::thread(&ServerSocket::clientsListener, this);
此外,您不需要像在 Java 中那样在同一行拼写两次类型,因此:
boost::thread clients_listener(&ServerSocket::clientsListener, this);
就足够了。
关于C++ 在类中创建线程给出 c2064,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25883715/