在标头中声明 sqlite::d atabase db( ":memory:" ) 会给出错误

Declaring sqlite::database db(":memory:") in header gives error

本文关键字:memory 错误 出错 atabase 声明 sqlite db      更新时间:2023-10-16

我正在使用其github页面上提供的sqlite_modern_cpp开发示例程序。我正在使用内存数据库。

在我的最终应用程序中,我需要将此数据库存储为我班级的私人成员。将数据库对象sqlite::database db(":memory:");称为私有时,我会遇到错误成员。当我将声明sqlite::database db(":memory:");移至源文件时,错误将解决。

#include <memory>
#include <sqlite_modern_cpp.h>
class sqlitemoderncpp
{
private :
    sqlite::database db(":memory:");   //Declaring in header gives error but all errors are resolved when moded to source file
public:
    void run();
};
void sqlitemoderncpp::run(void)
{

try {
        db <<
            "create table if not exists user ("
            "   _id integer primary key autoincrement not null,"
            "   age int,"
            "   name text,"
            "   weight real"
            ");";
        int age = 21;
        float weight = 68.5;
        std::string name = "jack";
        this->db << "insert into user (age,name,weight) values (?,?,?);" 
            << age
            << name
            << weight;
        std::cout << "The new record got assigned id " << this->db.last_insert_rowid() << std::endl;
        db << "select age,name,weight from user where age > ? ;"
            << 18
            >> [&](int age, std::string name, double weight) {
            std::cout << age << ' ' << name << ' ' << weight << std::endl;
        };
    }
    catch (std::exception& e) {
        std::cout << e.what() << std::endl;
    }
}

错误:

error C3867: 'sqlitecpp::db': non-standard syntax; use '&' to create a pointer to member 
error C2296: '<<': illegal, left operand has type 'sqlite::database (__cdecl sqlitecpp::* )(void)' 
error C2297: '<<': illegal, right operand has type 'const char [124]' 
error C3867: 'sqlitecpp::db': non-standard syntax; use '&' to create a pointer to member 
error C2296: '<<': illegal, left operand has type 'sqlite::database (__cdecl sqlitecpp::* )(void)' 
error C2297: '<<': illegal, right operand has type 'const char [51]' error 
C3867: 'sqlitecpp::db': non-standard syntax; use '&' to create a pointer to member error C2296: '<<': illegal, left operand has type 'sqlite::database (__cdecl sqlitecpp::* )(void)' 
error C2297: '<<': illegal, right operand has type 'const char [49]'

默认成员初始化程序(自C 11(仅适用于Brace或Equals Initializer。您可以将其更改为

sqlite::database db{":memory:"};

sqlite::database db = sqlite::database(":memory:");

在C 11之前,您可以添加带有成员初始化器列表的构造函数。

class sqlitemoderncpp
{
private :
    sqlite::database db;
public:
    void run();
    sqlitemoderncpp() : db(":memory:") {}
};
相关文章: