c++ - 不同来源的QT调用函数

标签 c++ qt function public

在我的项目中,我创建了多个图形用户界面页面。在辅助源 (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/

相关文章:

c++ - 通过 C++ 中的 udp 套接字将派生类对象从一个进程发送到另一个进程

c++ - 返回局部变量的地址与返回局部变量的指针

python - 具有可变参数的回调函数 tkinter 按钮

c++ - DBExpress和mysql最后插入id

用于 Symbian VS 的 Qt。用于 MeeGo 的 Qt

c++ - QT Creator 错误(与 operator+ 不匹配)

c++ - Qt C++ 和 QSerialDevice : Windows 7 USB->Serial Port Reading/Writing

c - 有没有重构工具可以自动将大函数拆分成小函数?

javascript - onClick 函数在另一个函数中

c++ - 在 unix 上从 c/c++ 断点/调试其他用户进程