2 phase constructor

来源:互联网 发布:咸鱼是淘宝网二手吗 编辑:程序博客网 时间:2024/05/29 19:05
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);
    }
 
原创粉丝点击