方法一:
利用引用计数:
#include <iostream>
using namespace std;
class Object
{
public:
~Object()
{
count=1;
}
Object()
{
if (count==0)
{
cout<<"该类只能创建一个对象!";
return ;
}
--count;
}
private:
static int count;
};
int Object::count=1;
int main()
{
Object b;
return 0;
}
方法二:利用友元函数
#include <iostream>
using namespace std;
class Object
{
public:
~Object(){}
private:
Object(){}
Object(const Object&){}
Object& operator =(const Object &){}
friend Object& CreateObject()
{
static Object a;
return a;
}
};
int main()
{
return 0;
}
本文出自 “pawnsir的IT之路” 博客,请务必保留此出处http://10743407.blog.51cto.com/10733407/1746507