单例中的构造函数重载不起作用

Constructor overloading in Singleton doesn't work

本文关键字:不起作用 重载 构造函数 单例中      更新时间:2023-10-16

我正在学习使用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;
}

在您的主函数中执行

singleton* a= singleton::getInstance();

因此,实例被设置为singleton从空构造函数中获得的值。然后你做

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

但是您忘记了flag是true,因为您在空构造函数中将其设置为true。所以这句话毫无意义。

在那之后,你在b上做的一切都和在a上做的一样,所以它不能像你想要的那样工作

main()函数交错执行单例的"构造"和销毁。

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

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