QT程式設計之——使用全域性變數

振長策而御宇內發表於2014-05-19

在Qt中使用全域性變數的例項
1.首先需要在一個標頭檔案中對全域性了變數使用exern方法進行定義。

//g.h
extern char *testStr;

2.只能在cpp檔案中對其例項化,並且例項化只能在函式的外部進行。建議在包含main函式的cpp檔案中進行例項化,這樣可以確保在其他檔案中使用時,它已經被例項化。

//a.h
#include "g.h"
char *testStr="hello world";
void main()
{
   cout<<testStr<<endl;
   testStr="hello China";
}



3. 其他檔案只要包含了g.h這個標頭檔案,就可以修改或者訪問這個全域性變數,而不需要再次例項化。

//b.h
//該檔案中就可以不需要例項化全域性變數了。
#include "g.h"
void mytest()
{
   cout<<testStr<<endl;
}

比如我在externData.h檔案中定義全域性變數

#ifndef EXTERNDATA_H
#define EXTERNDATA_H

#include "basicclassroom.h"

//定義所有房間資訊集合List全域性變數,其他檔案引用
QList<BasicClassRoom*>* roomList;

#endif // EXTERNDATA_H


我在main.cpp檔案中需要引用這個全域性變數,並宣告,需要初始化roomList,引用externData.h檔案

#include "excellenthomepage.h"
#include <QApplication>
#include <QTextCodec>
#include <QtDebug>
#include <QFile>
#include <QDate>
#include <QTextStream>
#include "qstringlist.h"
#include "externData.h"

extern QList<BasicClassRoom*>* roomList;

//根據配置檔案獲取所有房間資訊,儲存到全域性變數RoomList中
void getAllRoomList()
{
    //判斷是否有配置檔案
    roomList = new QList<BasicClassRoom*>();
    QString data = NULL;
    QTextCodec *codec = QTextCodec::codecForName("utf-8");

    QFile file("room.txt");
    if(file.exists()){
        file.open( QIODevice::ReadOnly| QIODevice::Text );
        QTextStream qts(&file);
        qts.setCodec(codec);
        data = codec->fromUnicode(qts.readAll());
        file.close();
    }

    QStringList sections = data.split("]"); //把每一個塊裝進一個QStringList中
    for(int j=0;j<sections.length()-1;j++)
    {
        BasicClassRoom *room = room->roomFromJsonData(sections.at(j));
        roomList->append(room);
        qDebug()<<"[AAAAAAAAAAA]"<<room->getRoomName();
        qDebug()<<"[BBBBBBBBBBB]"<<room->roomToJsonData();
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));//設定中文,解決顯示亂碼問題,一句話足矣

    getAllRoomList();

    ExcellentHomePage w;

    w.show();

    return a.exec();
}


我想在其他檔案中引用這個全域性變數,我不需要再引用externData.h檔案

#include "zonepageform.h"
#include "ui_zonepageform.h"
#include "basicclassroom.h"

extern QList<BasicClassRoom*>* roomList;

ZonePageForm::ZonePageForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ZonePageForm)
{
    ui->setupUi(this);
    roomSize = 0;
    //首先初始化介面中的元素
    ui->RoomLabel->setText(roomList->at(0)->getRoomName());
}




相關文章