将QLocalSocket *传递给期望QIODevice *的方法

时间:2011-01-07 00:40:57

标签: qt polymorphism qlocalsocket qtcpsocket

也许我过于雄心勃勃,但我正在尝试编写一个可以通过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风格演员或   功能式演员

现在指向的类型显然无关,在我的代码中的其他地方我没有任何问题,例如:

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

server = socket;

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

此致

斯蒂芬。

1 个答案:

答案 0 :(得分:1)

最可能的原因是您忘记了发生错误的源文件中的#include <QLocalSocket>