问题
I'm using Qt and in the main method I need to declare an object that I need to use in all my other files. How can I access that object in the other files? (I need to make it global..)
I'm use to iPhone development and there we have the appDelegate that you can use all over the application to reach objects you've declared in applicationDidFinishLaunching method. How can I do the same in Qt?
回答1:
global_objects.hpp
extern int myGlobalInt;
global_objects.cpp
#include "global_objects.hpp"
namespace
{
int myGlobalInt;
}
And then #include "global_objects.hpp"
in every place you need myGlobalInt
.
You should read C++ singleton vs. global static object and Initializing qt resources embedded in static library as well.
回答2:
In Qt there is the singleton QApplication, with its static method QApplication::instance() which gives you the one and only QApplication object back. It has many other static member functions (in an earlier age they were called "globals"), for the mainwindow, the active window etc.
http://doc.trolltech.com/4.5/qapplication.html
You can sublass it if you want to add your own statics.
回答3:
In general, you shouldn't use global variables in object oriented programming. In your case, you can solve the problem by providing static access functions to the variable in your main class. You should be aware, though, that this is somewhat contrary to OOP.
class MainClass
{
public:
static int mySharedValue(void) { return m_mySharedValue; }
static void setMySharedValue(int value) { m_mySharedValue = value; }
private:
static int m_mySharedValue;
}
Foo::myOtherClassFunction(void)
{
// do something
int bar = MainClass::mySharedValue();
// do some more
}
Furthermore, you can derive your main application from QApplication and add the access functions there, accessing the main object through the qApp
pointer provided by Qt.
Additionally to that you can always use a global variable the same way you can do in C, though I wouldn't recommend that.
来源:https://stackoverflow.com/questions/1471764/global-variable-in-qt-how-to