【问题标题】:How to restrict a Class on number of objects to be created in C++?如何限制要在 C++ 中创建的对象数量的类?
【发布时间】:2013-12-30 06:27:29
【问题描述】:

我只是在编写一个示例代码来从一个类中只创建 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;
}

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

【问题讨论】:

  • 快速响应Count = ++; 是语法错误。
  • 你是如何测试它的?你的期望是什么?
  • 我觉得这个link可以帮到你。

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


【解决方案1】:
#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;
}

【讨论】:

  • 常见的方法可能是在你的 SingletonGeneric 构造函数中设置 count++ 并在你的 SingletonGeneric 析构函数中设置 count-- 。还要检查 SingletonGeneric 构造函数中的 count = 5 则抛出异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
相关资源
最近更新 更多