我正在使用他们的 github 页面上提供的 sqlite_modern_cpp 开发一个示例程序。我正在使用内存数据库。
在我的最终应用程序中,我需要将该数据库存储为类的私有(private)成员。将数据库对象 sqlite::database db(":memory:");
声明为私有(private)时出现错误
成员。当我将声明 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]'
最佳答案
default member initializer (C++11 起) 仅适用于大括号或等于初始值设定项。您可以将其更改为
sqlite::database db{":memory:"};
或
sqlite::database db = sqlite::database(":memory:");
在 C++11 之前,您可以使用 member initializer list 添加构造函数.
class sqlitemoderncpp
{
private :
sqlite::database db;
public:
void run();
sqlitemoderncpp() : db(":memory:") {}
};
关于c++ - 在 header 中声明 sqlite::database db (":memory:") 会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56236162/