在我的项目中,我创建了多个图形用户界面页面。在辅助源 (secondary.cpp) 中,我想调用在我的 mainwindow.cpp
中声明的函数。我不太确定该怎么做。
我尝试在公共(public)部分声明函数,例如:
QString format (QString number);
mainwindow.cpp
中的定义如下:
QString MainWindow::format(QString number)
{
...
}
然后我在我的辅助源 (secondary.cpp
) 中包含 #include "mainwindow.h"
并使用 lower = format(upper) 调用该函数;
但我收到一条错误消息:
format was not declared in this scope.
我也试过调用它
lower = MainWindow::format(upper);
这给了我错误信息
Cannot call member function QString MainWindown::format(Qstring) without object.
最后我还尝试在我的 mainwindow.h
中创建一个类
class test : public QString
{
public:
QString format (QString number);
};
在我的 mainwindow.cpp
中使用 QString test::format(QString number)
通过 lower = test::format(upper);
这给了我错误:
Cannot call member function QString MainWindown::format(QString) without object.
我不确定我是否需要创建一个新类,但我想我还是会尝试一下。
最佳答案
您需要创建MainWindow
类的对象,然后调用函数:
MainWindow *w = new MainWindow;
QString lower = w->format(upper);
或者另一种解决方案是类的静态函数。这样你就不需要创建类的对象并且可以像这样按名称调用方法:
QString lower = MainWindow::format(upper);
当然,您需要包含您的#include "mainwindow.h"
header 。
但是你应该知道MainWindow
类不是存放字符串函数的最佳地方,你可以使用QString
类函数,如 QString::toUpper()
或 QString::toLower()
或创建您自己的格式化类:
class myFormatingStringClass {
QString toLower(QString str);
static QStrin toUpper(QString str);
}
正如我在上面所说的那样,您将需要创建 myFormatingStringClass
的对象以使用 myFormatingStringClass::toLower()
函数或使用静态方法:
QString upper = QString("Hello World");
myFormatingStringClass formating;
QString lower = formatin.toLower(upper); // Using class method of existing object
QString upper = myFormatingStringClass::toUpper(lower); // Using static method
关于c++ - 不同来源的QT调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31674870/