[英]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.