首 页 | 新 闻 | Symbian | Android| Windows Mobile | J2ME | 下载中心 | 游戏策划招聘与求职 | 购书指南 | 视频教程
您现在的位置: 开发视界 >> Symbian英文资料 >> Tips Tricks >> 正文
Simplify Two Phase Constructor in Symbian
作者:佚名    文章来源:不详    更新时间:2006-5-7 11:26:13

As we know that every time when we declare a class with initial C and derive from CBase we have to provide second phase constructor (NewL and NewLC ) in genral for such classes. There is a way which will give some flexibility to reduce to write NewL and NewLC evey time when you derive a class from CBase and need second phase constructor.

//Define a class which is base class like this:


//Phasebase.h base class for all classes derived from CBase
//and has second phase constructor
#include <e32def.h>
#include <e32base.h>

template <class T>
class CPhaseBase : public CBase
{
public:
  static T* NewL()
          {
          T* self = new (ELeave) T();
        CleanupStack::PushL(self);
        self->ConstructL();
        CleanupStack::Pop(self);
        return self;
          }
          static T* NewLC()
        {
        T* self = new (ELeave) T();
        CleanupStack::PushL(self);
        self->ConstructL();
        return self;
        }
public:
  //All classes derive from CPhasebase must implement   this function
  virtual void ConstructL() = 0 ;
};

and here is an example class which uses this class as base class

//UsePhase.h
#include "Phasebase.h"
class CUsePhase;
class CUsePhase : public CPhaseBase<CUsePhase>
{
private:
        HBufC* iMyBuf;
public:
        void ConstructL();
public:
        CUsePhase()
                {
                }
        ~CUsePhase();
};
//UsePhase.cpp
#include "UsePhase.h"

#define KMaxLength    50

void CUsePhase :: ConstructL()
{
        iMyBuf = HBufC::NewL(KMaxLength);
}

CUsePhase ::~CUsePhase()
{
        if(iMyBuf)
        {
        delete iMyBuf;
        iMyBuf = NULL;
        }
}

To use the class you simply need to do:

CUsePhase *iMyPhase;
iMyPhase = CUsePhase::NewL();

This will call templated NewL of CPhaseBase class and internally calls ConstructL of CUsePhase which is second phase constructor.

Note: if you want parameterized constructors then you must override NewL and NewLC and then from that has to call NewL of CPhaseBase.


Bhuvan.

相关文章:
Observer Pattern in Symbian application
Retrieving IMEI, IMSI, Network Info (Cell Id, Location Code) on 3rd Edition.
Hashtable implementation for Symbian
C++ Inheritance
Using Extended Notifiers
Cleanup support for ResetAndDestroy()
Guidelines for Code Optimisation
Estimate the Size of a Class/Object
 

站点地图 | 加入收藏 | 联系站长 | 广告服务 |
QQ:280529124  Tel:0592-8271361 辽ICP备05021703号