繁体   English   中英

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

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

我有两个文件:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM