【发布时间】:2013-08-28 01:55:45
【问题描述】:
我正在学习使用单例设计模式。我写了一个简单的代码,包括构造函数重载和一个终止函数来删除指针。问题是构造函数重载不起作用,它不需要 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;
}
【问题讨论】:
-
公平警告,单例是一种反模式。
-
单例的全部意义在于你只能创建一个对象。使用带有参数的构造函数的单例是没有意义的,因为这意味着您可以创建具有不同参数的多个对象。我想你不明白单例是干什么用的。也许你真正想要的是工厂模式?
-
定义:“不起作用”
-
使用 g++ 4.4.7 编译和运行良好,输出:64 64 Recover assigned mem : Success Recover assigned mem : Success RUN SUCCESSFUL (总时间: 64ms)
-
@john:一次也可以是一个选项(对于那些认为单例一开始就是一个选项的人)。无论如何,我都不会在
getInstance()函数中使用参数,但这是一个不同的问题(就像实现不是线程安全的或不需要bool标志...
标签: c++ singleton destructor constructor-overloading