如何在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("select Question, Answer, MainPosition, SecondPosition, IsMustReview
from Cards", myDataBase);
如何在头文件中声明它并在main.cpp
文件中全局使用?
实际上,您可以将getCardsQuery
声明为MainWindow
类的成员变量。下面的代码大致演示了如何做到这一点:
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();
[..]
}
}
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数