QT c++内部变量切换

QT c++ internal variable handover

本文关键字:变量 内部 c++ QT      更新时间:2023-10-16

我在mainwindow.h 中声明了一个int函数

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    int port();

此外,我在appendant mainwindow.cpp文件中声明了这个函数。

int MainWindow::port()
{
    int port_int;
    QString port_ei;
    if(ui->portInput->text() == 0)
    {
        port_ei = "6008";
        ui->textIncome->setPlainText(port_ei);
        port_int = port_ei.toInt();
    }
    else
    {
        port_ei = ui->portInput->text();
        ui->textIncome->setPlainText(port_ei);
        port_int = port_ei.toInt();
    }
    return port_int;
}

现在我想让我的服务器(在myserver.cpp文件中)监听那个端口。

MyServer::MyServer(QObject *parent) :
    QObject(parent)
{
    server = new QTcpServer(this);
    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
    int port_out =  MainWindow::port();
    if(!server->listen(QHostAddress::Any,port_out))
    {
        qDebug() << "Server could not start.";
    }
    else
    {
        qDebug() << "Server started.";
    }
}

但qt告诉我,我对一个非静态函数(在int port_out = MainWindow::port();行)进行了非法请求。如何解决?如果有两个单独的.cpp和.h文件(除了主.cpp之外),有没有更好的方法可以做到这一点。是的,我在两个cpp文件中都包含了"mainwindow.h"answers"myserver.h"。

MainWindow::port();是一个静态函数调用。但是port函数不是静态的,它需要像main_window->port()一样被调用,其中main_window是指向MainWindow对象的指针。