c++实例研究

从0开始

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  104 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks

 

#include <cstdlib>
#include 
<iostream>
using namespace std;

struct bottle
{
    
int refCount;
    
int weight;
    
int size;
    bottle(
int w,int sz):refCount(1),weight(w),size(sz){}
    bottle
* getOwnCopy()
    
{
        
if(refCount==1)
            
return this;
        refCount
--;
        
return new bottle(weight,size);
    }

private:
    bottle(
const bottle&);
    bottle
& operator=(const bottle&);
}
;

class ProductBottle
{
public:
    ProductBottle(
int w=10,int sz=20):pinst(new bottle(w,sz)){}
    ProductBottle(
const ProductBottle& other)
    
{
        other.pinst
->refCount++;
        pinst 
= other.pinst;
    }

    ProductBottle
& operator=(const ProductBottle& rhs)
    
{
        rhs.pinst
->refCount++;
        
if(--pinst->refCount==0)
            delete pinst;
        pinst 
= rhs.pinst;
        
return *this;
    }

    
~ProductBottle()
    
{
        
if(--pinst->refCount==0)
            delete pinst;
    }

    
int AddWater(int waterWeight)
    
{
        pinst 
= pinst->getOwnCopy(); 
        pinst
->weight += waterWeight;
        
return 0
    }

    
int show()
    
{
        cout
<<pinst->weight<<' '<<pinst->size<<' '<<pinst->refCount<<endl;
    }

private:
    bottle
* pinst;
}
;

int main()
{
    ProductBottle Cola;
    ProductBottle Sprint(Cola);
    ProductBottle Finda(Sprint);
    
/*****************************/
    Cola.show();
    Sprint.show();
    Finda.show();
    
/*****************************/
    Cola.AddWater(
50);
    
/*****************************/
    Cola.show();
    Sprint.show();
    Finda.show();
    
/*****************************/    
    system(
"PAUSE");
    
return 0;
}

posted on 2010-05-10 22:14 elprup 阅读(212) 评论(0)  编辑 收藏 引用 所属分类: c++实例

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理