实现一个类:不能被继承,而且最多只能有三个实例

来源:互联网 发布:js null与undefined 编辑:程序博客网 时间:2024/04/28 12:09
[cpp] view plaincopy
  1. class A  
  2. {  
  3. public:  
  4.     //this function is static !  
  5.     static A* instance(void)  
  6.     {  
  7.         if (n<3) { return new A; }  
  8.         else return (A*)0;  
  9.     }  
  10.     //this func is nont static !  
  11.     void print(voidconst { cout<<n<<endl;}  
  12. private:  
  13.     A(){ ++n;}  
  14.     static int n;  
  15. };  
  16. int A::n=0;//do not forget to init n  
  17.   
  18. int main( void )   
  19. {  
  20.    
  21.     A* p=NULL;  
  22.     for (int i=0;i<5;i++)  
  23.     {  
  24.         p=A::instance();  
  25.         if (p!=NULL)  
  26.         {  
  27.             p->print();  
  28.         }  
  29.     }  
  30.     return 0;  
  31. }  
原创粉丝点击