两阶构造函数练习_2
两阶构造函数练习_2
ConstructL 是每个 NewLC 必须调用的,ConstructL 体现出了两阶构造函数的实质,初始化操作放到 ConstructL函数中来操作,看下面的代码
头文件:
#include "OnePhbase.h"
#include <e32def.h> #include <e32std.h> class CTwoPhbase : public CBase
{ public:
TInt iInt1,iInt2; COnePhbase* iOnePhbase; RTimer iTimer; // 构造函数 static CTwoPhbase* NewL(TInt aInt); static CTwoPhbase* NewLC(TInt aInt); void Print(CConsoleBase* cone); protected: void ConstructL(TInt aInt); public: CTwoPhbase(); virtual ~CTwoPhbase(); };
代码文件:
#include "TwoPhbase.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction ////////////////////////////////////////////////////////////////////// CTwoPhbase::CTwoPhbase()
{ }
CTwoPhbase::~CTwoPhbase()
{ delete this->iOnePhbase; iTimer.Close(); } CTwoPhbase* CTwoPhbase::NewL( TInt aInt )
{ CTwoPhbase* self = CTwoPhbase::NewLC(aInt); CleanupStack::Pop(); return self; } CTwoPhbase* CTwoPhbase::NewLC( TInt aInt )
{ CTwoPhbase* self = new (ELeave) CTwoPhbase(); CleanupStack::PushL(self); self->ConstructL(aInt); return self; } void CTwoPhbase::ConstructL( TInt aInt )
{ iInt1 = aInt; User::LeaveIfError(iTimer.CreateLocal()); iOnePhbase = COnePhbase::NewL(); } void CTwoPhbase::Print(CConsoleBase* cone) { _LIT(KFormat2,"CTwoPhbase2 {TInt %d ,TInt %d ,RTime "); cone->Printf(KFormat2,iInt1,iInt2); iOnePhbase->Print(cone); _LIT(KTxtCloseCurly,"}"); cone->Printf(KTxtCloseCurly); } |
上面的代码中 _LIT 是定义一个描述符,RTime 是一个定时器,慢慢学习这个定时器
注意的是:在要析构函数中释放 NewL 产生的对像,不要释放 NewLC产生的对像,对于 NewL产生的对像,没有放到清除栈中,而 NewLC 会放到清除栈中,如果对于 NewLC
生成的对像,再通过析构函数去释放,会产生多次释放,程序出错
安平2009@原创
qi_jianzhou@126.com