0

也许我过于雄心勃勃,但我正在尝试编写一个服务器程序,它可以接受 QLocalSockets 和 QTcpSockets 上的连接。这个概念是有一个“nexus”对象,同时有一个 QLocalServer 和 QTcpServer 监听新连接:

    Nexus::Nexus(QObject *parent)
        : QObject(parent)
    {
        // Establish a QLocalServer to deal with local connection requests:
        localServer = new QLocalServer;

        connect(localServer, SIGNAL(newConnection()),
                this,        SLOT(newLocalConnection()));
        localServer -> listen("CalculationServer");


        // Establish a UDP socket to deal with discovery requests:
        udpServer = new QUdpSocket(this);
        udpServer -> bind(QHostAddress::Any, SERVER_DISCOVERY_PORT);
        connect(udpServer, SIGNAL(readyRead()),
                this,      SLOT(beDiscovered()));

        // Establish a QTcpServer to deal with remote connection requests:
        tcpServer = new QTcpServer;

        connect(tcpServer, SIGNAL(newConnection()),
                this,      SLOT(newTcpConnection()));
        tcpServer -> listen(QHostAddress::Any, SERVER_COMMAND_PORT);
    }

...然后分开建立服务器对象的插槽,其构造函数采用指向 QIODevice 的指针。理论上,这应该可以工作,因为 QLocalSocket 和 QTcpSocket 都继承了 QIODevice。这是 newLocalConnection 插槽,例如:

void Nexus::newLocalConnection()
{
    // Create a new CalculationServer connected to the newly-created local socket:
    serverList.append(new CalculationServer(localServer -> nextPendingConnection()));

    // We don't allow more than one local connection, so stop listening on the server:
    localServer -> close();
}

问题是这不会编译,给出一个错误:

错误 C2664:“CalculationServer::CalculationServer(QIODevice *,QObject *)”:无法将参数 1 从“QLocalSocket *”转换为“QIODevice *”1> 指向的类型不相关;转换需要 reinterpret_cast、C-style cast 或 function-style cast

现在指向的类型显然不是无关的,在我的代码的其他地方,我对以下操作完全没有问题:

QLocalSocket *socket = new QLocalSocket;
QIODevice    *server = new QIODevice;

server = socket;

...所以谁能告诉我为什么编译器有这个问题?有没有办法让构造函数接受 QLocalServer*?我想有一个核选项让构造函数接受一个 void 指针和一个额外的变量来告诉它它正在发送什么,因此它可以将 void 指针重新转换为 QLocalSocket 或 QTcpSocket,但我觉得诉诸 reinterpret_cast 感到不舒服看起来它应该是一个简单的 C++ 多态性。

问候,

斯蒂芬。

4

1 回答 1

1

最可能的原因是您忘记#include <QLocalSocket>在源文件中出现错误。

于 2011-01-07T03:26:38.487 回答