2 phase constructor

class  CStudent :  public  CBase
{
public:
    
static CStudent* NewLC(const TDesC& aName, TInt aNum);
    
static CStudent* NewL(const TDesC& aName, TInt aNum);

    TInt GetNum() 
const return iNum; }
    
const TDesC& GetName() const return *iName; }

    CStudent
& operator=(const CStudent& aStu);


    
static TInt CompareByNum(const CStudent& aStu1, const CStudent& aStu2);
    
~CStudent();

private:
    CStudent(TInt aNum);
    
void ConstructL(const TDesC& aName);
private:
    HBufC
* iName;
    TInt iNum;
}
;

CStudent
*  CStudent::NewLC( const  TDesC &  aName, TInt aNum)
{
    CStudent
* self = new(ELeave) CStudent(aNum);
    CleanupStack::PushL(self);
    self
->ConstructL(aName);

    
return self;
}


CStudent
*  CStudent::NewL( const  TDesC &  aName, TInt aNum)
{
    CStudent
* self = NewLC(aName, aNum);
    CleanupStack::Pop(self);

    
return self;
}


CStudent::CStudent(TInt aNum) : iNum(aNum) 
{ }

void  CStudent::ConstructL( const  TDesC &  aName)
{
    iName 
= aName.Alloc();
}


TInt CStudent::CompareByNum(
const  CStudent &  aStu1,  const  CStudent &  aStu2)
{
    
if (aStu1.GetNum() == aStu2.GetNum())
        
return 0;
    
else
        
return aStu1.GetNum() > aStu2.GetNum() ? 1 : -1;
}


CStudent
&  CStudent:: operator   = ( const  CStudent &  aStu)
{
    iNum 
= aStu.GetNum();

    delete iName;
    iName 
= aStu.GetName().Alloc();

    
return *this;
}


CStudent::
~ CStudent()
{
    delete iName;
    iName 
= NULL;
}


LOCAL_C 
void  MainL( const  TDesC &  aArgs)
    
{
        _LIT(KTom, 
"Tom");
        _LIT(KJack, 
"Jack");
        CStudent
* stu = CStudent::NewLC(KTom, 21);

        CStudent
* other = CStudent::NewLC(KJack, 33);

        
*stu = *other;
        console
->Printf(stu->GetName());
        console
->Printf(_L("%d"), stu->GetNum());
        
        CleanupStack::PopAndDestroy(other);
        CleanupStack::PopAndDestroy(stu);
    }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值