链接静态单例类

rkm*_*max 3 c++ linker singleton

当我尝试链接一个SIngleton类时得到

sources/singleton.cpp:8:41: error: no se puede declarar que la función miembro ‘static myspace::Singleton& myspace::Singleton::Instance()’ tenga enlace estático [-fpermissive]
sources/director.cpp:19:35: error: no se puede declarar que la función miembro ‘static void myspace::Singleton::Destroy()’ tenga enlace estático [-fpermissive]
myspace: *** [objects/singleton.o] Error 1
Run Code Online (Sandbox Code Playgroud)

Singleton类:

#Singleton.h
#include <stdlib.h>

namespace myspace {

    class Singleton
    {
    public:
        static Singleton& Instance();
        virtual ~Singleton(){};
    private:
        static Singleton* instance;
        static void Destroy();
        Singleton(){};
        Singleton(const Singleton& d){}
    };
}

#Singleton.cpp
#include "../includes/Singleton.h"

namespace myspace {
    Singleton* Singleton::instance = 0;

    static Singleton& Singleton::Instance()
    {
        if(0 == instance) {
            instance = new Singleton();

            atexit(&Destroy);
        }

        return *instance;
    }

    static void Singleton::Destroy()
    {
        if (instance != 0) delete instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要一些LDFLAGS到链接器?

Joa*_*son 7

您只能在声明中声明方法静态,在实现中不允许这样做.只需将您的实施更改为;

Singleton& Singleton::Instance()
{
Run Code Online (Sandbox Code Playgroud)

void Singleton::Destroy()
{
Run Code Online (Sandbox Code Playgroud)

你应该没事