我在mainwindow.h中声明了一个int函数
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
int port();
此外,我在附加的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文件(除了main.cpp之外),还有更好的方法吗?
是的,我在两个cpp文件中都包含了“mainwindow.h”和“myserver.h”。
答案 0 :(得分:1)
MainWindow::port();
是一个静态函数调用。但port
函数不是静态的,需要像main_window->port()
一样调用,其中main_window
是指向MainWindow
对象的指针。