如何使用受保护的函数setLocalPort?

时间:2019-07-19 13:40:01

标签: qt port qtcpsocket

我应该使用setlocalport进行套接字连接,但是该属性受到保护,并且编译时出现错误。

这是在qt应用程序中。

m_pSocket = new QTcpSocket();

m_pSocket->setLocalPort(m_iLocalPort);

错误:“ void QAbstractSocket :: setLocalPort(quint16)”受保护

1 个答案:

答案 0 :(得分:0)

如果要像公共成员一样使用受保护的成员,则应提供一个自定义类,该类是要使用其受保护方法的类的子级。没有什么可以禁止您创建继承QTcpSocket的子类,然后使用所需的受保护的方法。下面描述的QTcpSocket案例示例如下。

// Let us define CustomTcpSocket, i.e. the class inheriting QTcpSocket
#pragma once
#include <QTcpSocket>


class CustomTcpSocket
    : public QTcpSocket
{
    Q_OBJECT
public:
    CustomTcpSocket(QObject* parent = nullptr);
    virtual ~CustomTcpSocket();

    // This method will be used to call QTcpSocket::setLocalPort which is protected.
    void SetLocalPort(quint16 port);
};

然后,我们提供实现本身。

#include "CustomTcpSocket.h"

CustomTcpSocket::CustomTcpSocket(QObject* parent)
    : QTcpSocket(parent)
{
}

CustomTcpSocket::~CustomTcpSocket()
{
}

void CustomTcpSocket::SetLocalPort(quint16 port)
{
    // Since method is protected, and scope is the child one, we can easily call this method here.
    QAbstractSocket::setLocalPort(port);
}

现在,我们可以通过以下方式轻松使用这个新创建的类。

auto customTcpSocketInstance = new CustomTcpSocket();
customTcpSocketInstance->SetLocalPort(123456);

通过使用多态,其他Qt的API应该接受CustomTcpSocket的实例。但是,不能保证它会像您期望的那样工作。 Qt开发人员出于某些原因希望保护此方法。因此,请谨慎使用。