我正在编写服务器是多线程的客户端服务器程序,我想使用while()在我的线程中创建循环,但它在myhthread.cpp中收到以下错误: “预期')'之前'ID'” 我知道我的问题是基本的,但我真的很困惑...我怎么能为它创建循环?这是我的代码:
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QMainWindow>
#include <QTcpServer>
#include <QTcpSocket>
#include "myserver.h"
#include <QDebug>
class mythread : public QThread
{
Q_OBJECT
public:
mythread(qintptr ID, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
}
void run()
{
qDebug() << " Thread started";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
// if (m_client)
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
qDebug() << socketDescriptor << " Client connected";
exec();
}
signals:
void error(QTcpSocket::SocketError socketerror);
public slots:
void readyRead();
void disconnected();
private:
QTcpSocket* socket;
qintptr socketDescriptor;
};
#endif
mythread.cpp:
#include "mythread.h"
#include "myserver.h"
mythread(qintptr ID, QObject *parent) :
{
while(disconnected)
{
mythread::run();
}
}
void mythread::readyRead()
{
QByteArray Data = socket->readAll();
qDebug()<< " Data in: " << Data;
socket->write(Data);
}
void mythread::disconnected()
{
qDebug() << " Disconnected";
socket->deleteLater();
exit(0);
}
答案 0 :(得分:1)
在cpp的构造函数定义中使用范围解析,并删除行尾的:
:
mythread::mythread(qintptr ID, QObject *parent) // :
{
...
}
如果没有mythread::
前缀,编译器会理解您要声明某些类型为mythread
的对象,并且会被语法混淆。
编辑,一旦你纠正了错误,编译器会引起你的注意,你有两个相同构造函数的定义,这是非法的。
可能的更正:您应该清除所有函数实现的标头中的类声明,并将实现移动到cpp文件。由于您有两种不同的构造函数实现,您可以尝试合并两者:
//in the header: no implementation of functions
class mythread : public QThread
{
...
mythread(qintptr ID, QObject *parent);
void run();
...
};
// in the cpp
mythread(qintptr ID, QObject *parent)
: QThread(parent)
{
this->socketDescriptor = ID;
while(disconnected) // if you really want to do this during the construction
{
mythread::run();
}
}
void mythread::run()
{
...
}