Reputation: 23
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
Upvotes: 0
Views: 204
Reputation: 140
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;
}
};
Upvotes: 0
Reputation: 29744
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
Upvotes: 0
Reputation: 21250
I think you need to remove the static
keyword from your static function definition:
Wrong:
static DatabaseEngine& DatabaseEngine::instance()
Correct:
DatabaseEngine& DatabaseEngine::instance()
Upvotes: 2