如何限制Class在C ++中创建的对象数量?

时间:2013-12-30 06:27:29

标签: c++ singleton static-methods static-members

我只是编写一个示例代码,只从类中创建5个对象。我写了这样的代码

#include <iostream>

using namespace std;

class SingletonGeneric
{
private:
    static int Count;
    static SingletonGeneric *single;
    SingletonGeneric()
    {
        //private constructor
    }
public:
    static SingletonGeneric* getInstance();
    void method();
    ~SingletonGeneric()
    {
        Count -- ;
    }
};

int SingletonGeneric::Count = 0;
SingletonGeneric* SingletonGeneric::single = NULL;
SingletonGeneric* SingletonGeneric::getInstance()
{
    if( Count >= 0 && Count < 6)
    {
        single = new SingletonGeneric();
        Count = ++;
        return single;
    }
    else
    {
        return single;
    }
}

void SingletonGeneric::method()
{
    cout << "Method of the SingletonGeneric class" << endl;
}
int main()
{
    SingletonGeneric *sc1,*sc2;
    sc1 = SingletonGeneric::getInstance();
    sc1->method();
    sc2 = SingletonGeneric::getInstance();
    sc2->method();

    return 0;
}

但我没有得到预期的结果。所以请告诉我应该如何修改我的代码。或者,如果还有其他简单的方法,请告诉我。

1 个答案:

答案 0 :(得分:0)

#include <iostream>

using namespace std;

class SingletonGeneric
{
private:
    static int Count;
    static SingletonGeneric *single;
    SingletonGeneric()
    {
        //private constructor
    }
public:
    static SingletonGeneric* getInstance();
    void method();
    ~SingletonGeneric()
    {
        Count -- ;
    }
};

int SingletonGeneric::Count = 0;
SingletonGeneric* SingletonGeneric::single = NULL;
SingletonGeneric* SingletonGeneric::getInstance()
{
    if( Count >= 0 && Count < 5) // should be 5 not 6
    {
        single = new SingletonGeneric();
        Count++;
        return single;
    }
    else
    {
        return NULL;// not the old single
    }
}

void SingletonGeneric::method()
{
    cout << "Method of the SingletonGeneric class" << endl;
}
int main()
{
    SingletonGeneric *sc1,*sc2, *sc3, *sc4, *sc5, *sc6;
    sc1 = SingletonGeneric::getInstance();
    sc1->method();
    sc2 = SingletonGeneric::getInstance();
    sc2->method();
    sc3 = SingletonGeneric::getInstance();
    sc3->method();
    sc4 = SingletonGeneric::getInstance();
    sc4->method();
    sc5 = SingletonGeneric::getInstance();
    sc5->method();
    sc6 = SingletonGeneric::getInstance();
    if (sc6 != NULL) {
        sc5->method();
    } else {
        cout << "only have to create 5 objects" << endl;
    }

    return 0;
}