笔试面试让写个单例,不一定每个人都能搞出来。我们以前也谈论过单例,现在继续来看看:
可以写为:
#include <iostream>
using namespace std;
class A
{
private:
int x;
static A *pInstance;
public:
void set(int m)
{
x = m;
}
int get()
{
return x;
}
static A *getInstance();
};
A * A::getInstance()
{
static A *pInstance = NULL;
if(NULL == pInstance)
{
pInstance = new A;
}
return pInstance;
}
int main()
{
A *p1 = A::getInstance();
A *p2 = A::getInstance();
if(p1 == p2)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
return 0;
}
但是,下面有错:
#include <iostream>
using namespace std;
class A
{
private:
int x;
static A *pInstance;
public:
void set(int m)
{
x = m;
}
int get()
{
return x;
}
static A *getInstance();
};
static A * A::getInstance()
{
static A *pInstance = NULL;
if(NULL == pInstance)
{
pInstance = new A;
}
return pInstance;
}
int main()
{
A *p1 = A::getInstance();
A *p2 = A::getInstance();
if(p1 == p2)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
return 0;
}
下面也有错:
#include <iostream>
using namespace std;
class A
{
private:
int x;
static A *pInstance;
public:
void set(int m)
{
x = m;
}
int get()
{
return x;
}
static A *getInstance();
};
A * A::getInstance()
{
pInstance = NULL;
if(NULL == pInstance)
{
pInstance = new A;
}
return pInstance;
}
int main()
{
A *p1 = A::getInstance();
A *p2 = A::getInstance();
if(p1 == p2)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
return 0;
}
奇葩的是,下面也有错:
#include <iostream>
using namespace std;
class A
{
private:
int x;
static A *pInstance;
public:
void set(int m)
{
x = m;
}
int get()
{
return x;
}
static A *getInstance()
{
pInstance = NULL;
if(NULL == pInstance)
{
pInstance = new A;
}
return pInstance;
}
};
int main()
{
A *p1 = A::getInstance();
A *p2 = A::getInstance();
if(p1 == p2)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
return 0;
}
你需要写成如下才好啊:
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
void set(int m)
{
x = m;
}
int get()
{
return x;
}
static A *getInstance()
{
static A* pInstance = NULL;
if(NULL == pInstance)
{
pInstance = new A;
}
return pInstance;
}
};
int main()
{
A *p1 = A::getInstance();
A *p2 = A::getInstance();
if(p1 == p2)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
return 0;
}
当然,如果你愿意,不用成员变量,而是用成员函数的局部静态变量或者该文件的全局静态变量表示单例,也是可以的。 多尝试,多观察,多总结吧。 我始终觉得,搞得面试,很少人能完全一次搞定这些,我在其内。