Reputation: 25
In my project I've created multiple gui pages. In a secondary source (secondary.cpp) I want to call a function that declared in my mainwindow.cpp
. I'm not really sure how to do this.
I've tried to declare the function at public section like:
QString format (QString number);
And definition in the mainwindow.cpp
like:
QString MainWindow::format(QString number)
{
...
}
Then i include #include "mainwindow.h"
in my secondary source (secondary.cpp
) and calling the function with lower = format(upper);
but I'm getting an error message:
format was not declared in this scope.
I've also tried calling it by
lower = MainWindow::format(upper);
which gives me the error message
Cannot call member function QString MainWindown::format(Qstring) without object.
Finaly I also tried to make a class in my mainwindow.h
class test : public QString
{
public:
QString format (QString number);
};
With QString test::format(QString number)
in my mainwindow.cpp
calling the function by lower = test::format(upper);
this gives me the error:
Cannot call member function QString MainWindown::format(QString) without object.
I'm not convinced that I need to create a new class, but I thought I'd try anyway.
Upvotes: 0
Views: 2165
Reputation: 1412
You need to create object of MainWindow
class, then call function:
MainWindow *w = new MainWindow;
QString lower = w->format(upper);
Or another solution is static function of class. This way you have no needed create object of class and can call method by name like this:
QString lower = MainWindow::format(upper);
Of course you need to include your #include "mainwindow.h"
header.
But you should know that MainWindow
class is not the best place storing function for formation string, you can use QString
class function like QString::toUpper()
or QString::toLower()
or create your own class for formating:
class myFormatingStringClass {
QString toLower(QString str);
static QStrin toUpper(QString str);
}
As i said above this way you will need to create object of myFormatingStringClass
for using myFormatingStringClass::toLower()
function or using static method:
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
Upvotes: 2
Reputation: 3389
You can't do test::format(...)
to call a non-static member function.
It must be bound to an object (an instance of your class
). For example, you can do this :
test testObject;
QString formattedString = testObject.format(strToFormat);
Upvotes: 1