方法一:
利用引用计数:
#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; }
时间: 2024-10-12 16:20:48