سؤال

i need help to figure out what wrong about that code:

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: error: LNK2019: unresolved external symbol "public: static class DatabaseEngine & __cdecl DatabaseEngine::instance(void)" (?instance@DatabaseEngine@@SAAAV1@XZ) referenced in function "public: __thiscall UsersWindow::UsersWindow(class QWidget *)" (??0UsersWindow@@QAE@PAVQWidget@@@Z)

userswindow.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall DatabaseEngine::do_something(void)" (?do_something@DatabaseEngine@@QAEXXZ) referenced in function "public: __thiscall UsersWindow::UsersWindow(class QWidget *)" (??0UsersWindow@@QAE@PAVQWidget@@@Z)

thanks

هل كانت مفيدة؟

المحلول

I think you need to remove the static keyword from your static function definition:

Wrong:

static DatabaseEngine& DatabaseEngine::instance()

Correct:

DatabaseEngine& DatabaseEngine::instance()

نصائح أخرى

declaration:

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

definition:

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

also make sure DatabaseEngine.cpp file is included in your project and is being compiled

You can use static variable in the static method instance to hold the unique instance and return the pointer. This is also a smart advice from Effective C++ I think. The example is untested but it should work

class DatabaseEngine
{
public:
    static DatabaseEngine& instance(){
        static DatabaseEngine db;
        return db;
    }
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top