我需要帮助来弄清楚该代码有什么问题:
class DatabaseEngine
{
protected:
DatabaseEngine();
static DatabaseEngine* m_DatabaseEngine;
public:
static DatabaseEngine& instance();
void do_something();
};
CPP:
#include "databaseengine.h"
DatabaseEngine* DatabaseEngine::m_DatabaseEngine=nullptr;
DatabaseEngine::DatabaseEngine()
{
}
static DatabaseEngine& DatabaseEngine:: instance()
{
if(m_DatabaseEngine==nullptr)
{
m_DatabaseEngine=new DatabaseEngine;`enter code here`
}
return *m_DatabaseEngine;
}
void DatabaseEngine::do_something()
{
}
userwindow.cpp:
#include "databaseengine.h"
UsersWindow::UsersWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::UsersWindow)
{
ui->setupUi(this);
DatabaseEngine::instance().do_something();
}
UsersWindow::~UsersWindow()
{
delete ui;
}
userswindow.obj:-1:错误:LNK2019:未解析的外部符号“public:static class DatabaseEngine& __cdecl DatabaseEngine :: instance(void)”(?instance @ DatabaseEngine @@ SAAAV1 @ XZ)在函数“public”中引用:__thiscall UsersWindow :: UsersWindow(class QWidget *)“(?? 0UsersWindow @@ QAE @ PAVQWidget @@@ Z)
userswindow.obj:-1:错误:LNK2019:未解析的外部符号“public:void __thiscall DatabaseEngine :: do_something(void)”(?do_something @ DatabaseEngine @@ QAEXXZ)在函数“public:__thiscall UsersWindow :: UsersWindow”中引用(班级QWidget *)“(?? 0UsersWindow @@ QAE @ PAVQWidget @@@ Z)
感谢
答案 0 :(得分:2)
我认为您需要从静态函数定义中删除static
关键字:
错:
static DatabaseEngine& DatabaseEngine::instance()
正确:
DatabaseEngine& DatabaseEngine::instance()
答案 1 :(得分:0)
声明:
static DatabaseEngine& DatabaseEngine::instance();
^
only in declaration
定义:
DatabaseEngine& DatabaseEngine:: instance() {
// code here
}
还要确保DatabaseEngine.cpp文件包含在您的项目中并正在编译
答案 2 :(得分:0)
您可以在静态方法实例中使用静态变量来保存唯一实例并返回指针。这也是我认为的Effective C ++的一个聪明建议。该示例未经测试但应该可以正常工作
class DatabaseEngine
{
public:
static DatabaseEngine& instance(){
static DatabaseEngine db;
return db;
}
};