如何在c++头文件中声明对象的构造函数后使用全局对象

how to use object global after declaring its constructor in header file in c++?

本文关键字:对象 构造函数 全局 声明 c++ 文件      更新时间:2023-10-16

我有两个文件:

// 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全局。我想这样初始化它:

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

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

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

在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();
        [..] 
    }
}