0

我需要帮助来弄清楚该代码有什么问题:

class DatabaseEngine
{
protected:
    DatabaseEngine();
    static DatabaseEngine* m_DatabaseEngine;
public:
    static DatabaseEngine& instance();
    void do_something();
};

cp:

#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()
{

}

用户窗口.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(class QWidget) 中引用*)" (??0UsersWindow@@QAE@PAVQWidget@@@Z)

谢谢

4

3 回答 3

2

我认为您需要static从静态函数定义中删除关键字:

错误的:

static DatabaseEngine& DatabaseEngine::instance()

正确的:

DatabaseEngine& DatabaseEngine::instance()
于 2013-11-01T22:08:55.033 回答
0

宣言:

static DatabaseEngine& DatabaseEngine::instance();
   ^
only in declaration

定义:

DatabaseEngine& DatabaseEngine:: instance() {
   // code here
}

还要确保 DatabaseEngine.cpp 文件包含在您的项目中并且正在编译

于 2013-11-01T22:11:37.747 回答
0

您可以在静态方法实例中使用静态变量来保存唯一实例并返回指针。我认为这也是来自 Effective C++ 的明智建议。该示例未经测试,但应该可以工作

class DatabaseEngine
{
public:
    static DatabaseEngine& instance(){
        static DatabaseEngine db;
        return db;
    }
};
于 2017-10-13T11:41:23.437 回答