我需要从sqlite回调函数中访问类中的变量。它不能是静态的,因为我需要从其他函数访问这些变量。这是我目前的代码。
class fromdb {
private:
string paramdb;
char* errmsg;
string param;
string title;
string creator;
char* bin;
public:
static int callback(void *data, int argc, char **argv, char **azColName){
int lenght;
lenght = sizeof(*argv[3]);
title = *argv[1];
creator = *argv[2];
bin = new char[lenght];
bin = argv[3];
return 0;
}
void getdata() {
string tQuery = "SELECT * FROM test WHERE " + paramdb + "=\"" + param + "\" )";
sqlite3_exec(db, tQuery.c_str(), fromdb::callback, (void*)data, &errmsg);
}
};
日志
undefined reference to `fromdb::title[abi:cxx11]'
undefined reference to `fromdb::creator[abi:cxx11]'
undefined reference to `fromdb::bin'
答案 0 :(得分:1)
您正在获取未定义的引用,因为您正在尝试使用静态函数中的非静态成员。
它不能是静态的,因为我需要从其他函数访问这些变量
您仍然可以使用static
功能,但您需要将成员传递为@Richard Critten points out in the comments,或者您可以使用friend
功能。
在这里,我创建了一个更简单的代码版本,使用像您一样的static
函数进行演示,但是传入成员变量:
class artwork
{
private:
std::string title;
std::string creator;
public:
static int populateFromDB(void* object, int, char** data, char**)
{
if (artwork* const art= static_cast<artwork*>(object))
{
art->title = data[1];
art->creator = data[2];
}
return 0;
}
};
artwork a;
char* error = nullptr;
if (sqlite3_exec(db, tQuery.c_str(), &artwork::populateFromDB, static_cast<void*>(&a), &error) != SQLITE_OK)
sqlite_free(error)
或者改为friend
函数:
class artwork
{
friend int getArtwork(void*, int, char**, char**);
private:
std::string title;
std::string creator;
};
int getArtwork(void* object, int, char** data, char**)
{
if (artwork* const art = static_cast<artwork*>(object))
{
art->title = data[1];
art->creator = data[2];
}
return 0;
}
artwork a;
char* error = nullptr;
if (sqlite3_exec(db, tQuery.c_str(), &getArtwork, static_cast<void*>(&a), &error) != SQLITE_OK)
sqlite_free(error)