链接静态单例类

3
当我尝试链接一个 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

单例模式类:

#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;
    }
}

我需要为链接器添加一些LDFLAGS吗?

1
提示:在此发布问题时,以及在互联网上搜索时,使用英文错误字符串通常是个好主意。在大多数 POSIX 环境中,可以通过在命令前加上“LANG=C”来临时请求英文输出。因此,例如 LANG=C make 将为您提供一个可搜索和可发布的良好错误字符串。 - Rawler
感谢 @Rawler,我在这个主题上是新手。我会记住的。 - rkmax
2个回答

7

只有在声明中才能将方法声明为静态,而在实现中是不被允许的。只需将您的实现更改为以下内容:

Singleton& Singleton::Instance()
{

并且

void Singleton::Destroy()
{

只要你按照正确的方法操作,就不会出现问题。


4

你需要从cpp文件中的定义中删除static:编译器已经从它们的声明中知道Singleton::InstanceSingleton::Destroystatic的。其他所有内容都看起来正确。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接