在C ++中的单例类 [英] Singleton Class in C++

查看:106
本文介绍了在C ++中的单例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用单例calss以下示例:

I have used singleton calss following the example:

singleton类

但我得到的错误为未解决的外部符号

这是我试过的代码:

#include<iostream>
using namespace std;

class singleton
{
    int value;
    static singleton *instance;
protected:
    singleton()
    {
        value=0;
    }
public:
    static void initialize()
    {
        if(instance==NULL)
            singleton();
        else
            cout<<"An instance of singleton already exist...";
    }
    static singleton& getInstance()
    { 
        return *instance; 
    }
    int getValue() 
    { 
        return value; 
    }

};

void main()
{
    singleton::initialize();
}

对Singleton类的一点解释真的很棒。使用的场景。优点和缺点。 Singleton的替代软件

A little bit explanation on Singleton classes would be really great. The scenario its used. advantages and drawbacks. Alternatives to Singleton. etc

推荐答案

首先,我想:

singleton();

应为:

instance = new singleton();

你的方式,你实际上并不存储新实例化的对象,所以<$ c $

The way you have it, you're not actually storing the newly instantiated object so instance will always be null.

这也是一个很好的形式显式设置静态:

It's also good form to explicitly set statics with:

singleton *singleton::instance = 0;

(在类定义之外)。

事实上,最好从基线单例代码开始,并从那里开始工作。这是一个标准形式的指针版本:

In fact, it's possibly better to start with the baseline singleton code and work your way up from there. This is a standard-form pointer version:

#include <iostream>

class singleton {
    protected:
        static singleton *instance;
        singleton() { }
    public:
        static singleton *getInstance() {
            if (instance == 0)
                instance = new singleton();
            return instance;
        }
};
singleton *singleton::instance = 0;

int main() {
    singleton *s1 = singleton::getInstance();
    singleton *s2 = singleton::getInstance();
    std::cout << s1 << '\n';
    std::cout << s2 << '\n';
    return 0;
}

您可以看到两个指针与输出相同:

You can see that both pointers are the same from the output:

0xbc0358
0xbc0358


b $ b

或参考版本,因为这似乎是你的目标:

Or the reference version, since that seems to be what you're aiming for:

#include <iostream>

class singleton {
    protected:
        static singleton *instance;
        singleton() { }
    public:
        static singleton& getInstance() {
            if (instance == 0)
                instance = new singleton();
            return *instance;
        }
};
singleton *singleton::instance = 0;

int main() {
    singleton &s1 = singleton::getInstance();
    singleton &s2 = singleton::getInstance();
    std::cout << &s1 << '\n';
    std::cout << &s2 << '\n';
    return 0;
}

这篇关于在C ++中的单例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆