我正在编写该服务器是多线程的客户端服务器程序,我想使用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);

}

最佳答案

在cpp中的构造函数的定义中使用范围解析,并在行末尾摆脱::

mythread::mythread(qintptr ID, QObject *parent) // :
{
    ...
}

如果没有mythread::前缀,则编译器会理解您要声明mythread类型的某个对象,并且语法感到困惑。

编辑:正如Danh所指出的,,纠正错误后,编译器将引起您的注意,即您具有同一构造函数的两个定义,这是非法的。

可能的更正:,应清除所有函数实现的 header 中的类声明,并将实现移至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()
 {
     ...
 }

10-08 11:54