3

我正在学习使用单例设计模式。我写了一个简单的代码,包括构造函数重载和一个终止函数来删除指针。问题是构造函数重载不起作用,它不需要 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;
}
4

2 回答 2

3

在你的主要功能中

singleton* a= singleton::getInstance();

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

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

但是您忘记了这flag是真的,因为您在空构造函数中将其设置为 true。所以这条线是没有意义的。

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

于 2013-08-25T13:46:11.923 回答
1

main()函数将单例的“构造”和销毁交错。

我不确定你的预期,但如果两个指针分开ab你会得到不同的输出。

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

于 2013-08-25T13:55:00.300 回答