如何在c ++中的头文件中声明构造函数后使用object global?

时间:2014-08-14 12:28:31

标签: c++ qt

我有两个文件:

// main.h
// some code ...

QSqlQuery getCardsQuery;
void readCardsFromDataBase();
void createCard();

//some code
// continue and end of main.h


//main.cpp
void MainWindow::readCardsFromDataBase()
{
    myDataBase = QSqlDatabase::addDatabase("QMYSQL", "my_sql_db");
    myDataBase.setHostName("localhost");
    myDataBase.setDatabaseName("Learn");
    myDataBase.setUserName("root");
    myDataBase.setPassword("password");
    bool ok = myDataBase.open();
    qDebug()<< ok;
    if (!ok)
        QMessageBox::warning(this, "connection Error", "cannot connect to DataBase");
    getCardsQuery("select Question, Answer, MainPosition, SecondPosition, IsMustReview\
                        from Cards", myDataBase);  // I got error in here
///error: no match for call to '(QSqlQuery) (const char [106], QSqlDatabase&)'

}

void MainWindow::createCard()
{
    getCardsQuery.next();
    card = new Card(getCardsQuery.value(0).toString(), getCardsQuery.value(1).toString());
    card->setPos(getCardsQuery.value(3).toInt(), getCardsQuery.value(4).toInt());
    card->setReviewToday(getCardsQuery.value(4).toBool());
}

初始化getCardsQuery时出错。我想使用getCardsQuery global.I想要像这样初始化它:

getCardsQuery("select Question, Answer, MainPosition, SecondPosition, IsMustReview\
                        from Cards", myDataBase);

如何在头文件中声明它并在main.cpp文件中全局使用?

1 个答案:

答案 0 :(得分:0)

实际上,您可以将getCardsQuery声明为MainWindow班级&#39;成员变量。下面的代码大致演示了如何做到这一点:

在main.h中

class MainWindow : public QMainWindow
{
[..]
private:
    QSqlQuery *getCardsQuery;
};

在main.cpp

MainWindow::MainWindow()
: getCardsQuery(0)
{}

void MainWindow::readCardsFromDataBase()
{
    [..]
    if (!getCardsQuery) {
        getCardsQuery = new QSqlQuery("select Question, Answer," \
                                      "MainPosition, SecondPosition," \
                                      "IsMustReview from Cards", myDataBase);
    }
    [..]
}

void MainWindow::createCard()
{
    if (!getCardsQuery) {
        getCardsQuery->next();
        [..] 
    }
}