Qt build时出现一个错createconnection was not declared in this scope
代码如下:
头文件connection.h:
#ifndef CONNECTION_H
#define CONNECTION_H
#ifndef CONNECTION_H
#define CONNECTION_H
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase(“QSQLITE”);
db.setDatabaseName(“:memory:”);
if (!db.open()) {
QMessageBox::critical(0, qApp->tr(“Cannot open database”),
qApp->tr(“Unable to establish a database connection.”
), QMessageBox::Cancel);
return false;
}
QSqlQuery query;
query.exec(“create table student (id int primary key, ”
“name varchar(20))”);
query.exec(“insert into student values(0, ‘first’)”);
query.exec(“insert into student values(1, ‘second’)”);
query.exec(“insert into student values(2, ‘third’)”);
query.exec(“insert into student values(3, ‘fourth’)”);
query.exec(“insert into student values(4, ‘fifth’)”);
return true;
}
#endif // CONNECTION_H
头文件widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
源文件main.cpp:
#include "widget.h"
#include "connection.h"
#include <QApplication>
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (!createConnection())
return 1;
Widget w;
w.show();
return a.exec();
}
源文件widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QSqlQuery>
#include <QtDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}#ifndef CONNECTION_H
#define CONNECTION_H
多了2个这个。我把你static 函数里面注释掉了 去掉上面多余的2个@ifndef能编过 mingw编译器