单例中的构造函数重载不起作用
Constructor overloading in Singleton doesn't work
我正在学习使用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()
函数交错执行单例的"构造"和销毁。
我不确定您期望的是什么,但如果两个指针a
和b
分开,您将得到不同的输出。
因为a
和b
都指向同一个对象,所以对getArea()
的调用将返回相同的结果。
相关文章:
- 重载运算符 (<<) cout 在 c ++ 中不起作用,当我互相减去两个矩阵时不起作用
- 为什么重载运算符>在参数声明 const 时不起作用?
- 重载"+="运算符:c+=a_times_b 有效,但 c+=a*b 不起作用?
- = 重载不起作用
- 类中的重载函数(Students())是输出输入的信息,但它不起作用
- 为什么 SFINAE 在这个简单的成员函数重载中不起作用
- C++ 运算符重载 += 有效,但<<不起作用
- 需要使用 Book* 头变量重载运算符,但不起作用
- C++ 运算符删除重载对派生类不起作用
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- 运算符重载如何工作,为什么在我的情况下不起作用?
- 为什么重载运算符不起作用?
- 重载'='不起作用
- 二叉搜索树<<运算符重载不起作用
- 重载运算符<<不起作用
- 重新赋值在运算符中不起作用 = 重载
- 类构造函数重载不起作用
- c++中的函数重载不起作用
- 为什么 [] 的重载函数在这里不起作用?
- 如果重载函数仅被部分重写,则多态性不起作用