在Singleton中构造函数重载不起作用

时间:2013-08-25 13:32:47

标签: c++ singleton destructor constructor-overloading

我正在学习使用Singleton设计模式。我写了一个简单的代码,包括构造函数重载和终止函数来删除指针。问题是构造函数重载不起作用,它不需要2个参数。我想不通为什么?

//header============================================
#include <iostream>
using namespace std;

class singleton
{
public:
        static singleton* getInstance();
        static singleton* getInstance(int wIn,int lIn);
        static void terminate();// memmory management
        int getArea();// just to test the output


private:
        static bool flag;
        singleton(int wIn, int lIn);
        singleton();
        static singleton* single;
        int width,len;
};

//implement=============================
#include "singleton.h"
#include <iostream>

using namespace std;

int singleton::getArea(){
        return width*len;
}
singleton* singleton::getInstance(int wIn,int lIn){

        if (!flag)
        {
                single= new singleton(wIn,lIn);
                flag= true;
                return single;
        }
        else
                return single;
}

singleton* singleton::getInstance(){
        if (!flag)
        {
                single= new singleton;
                flag=true;
                return single;
        }
        else
        {
                return single;
        }
}

void singleton::terminate(){

        delete single;
        single= NULL;
        perror("Recover allocated mem ");
}


singleton::singleton(int wIn,int lIn){

        width= wIn;
        len= lIn;
}

singleton::singleton(){
        width= 8;
        len= 8;
}
//main=======================================
#include <iostream>
#include "singleton.h"

bool singleton::flag= false;
singleton* singleton::single= NULL;

int main(){

        singleton* a= singleton::getInstance();
        singleton* b= singleton::getInstance(9,12);
        cout << a->getArea()<<endl;
        //a->terminate();
        cout << b->getArea()<<endl;
        a->terminate();
        b->terminate();
        return 0;
}

2 个答案:

答案 0 :(得分:2)

在你的主要功能中

singleton* a= singleton::getInstance();

所以实例设置为单例从空构造函数获得的值。然后你做

singleton* b= singleton::getInstance(9,12);

但是你忘了flag是真的,因为你在空构造函数中将它设置为true。所以这条线毫无意义。

之后,你在b上做的一切都和你在a上做的一样,所以它不能按你的意愿工作

答案 1 :(得分:1)

main()函数交错了“构造”和破坏单例。

我不确定您的期望,但如果两个指针ab分开,您将获得不同的输出。

由于ab都指向同一个对象,因此对getArea()的调用将返回相同的结果。