现在的位置: 首页 > 综合 > 正文

static_cast在ATL中很常见.它是实现模版形式多态的关键.

2014年01月17日 ⁄ 综合 ⁄ 共 840字 ⁄ 字号 评论关闭
 static_cast在ATL中很常见.它是实现模版形式多态的关键.

比如:
template <class   T>
class   CTest:public   T
{
      ....
   
      void   SomeMethod()
      {
              T   *pT   =   static_cast <T*> (this);
              pT-> BaseMethod();
      }
};

初看很迷惑,既然CTest继承自T,直接调用T中BaseMethod()不就行了.为什么作 "T   *pT   =   static_cast <T*> (this); "这样的转换?

其实,这正是模版方式实现多态的关键.

先看看类的实现:

class   CBase
{
public:
        CBase(){};
        ~CBase(){};

        void   BaseMethod()
        {
              cout   < <   "BaseMethod   in   Base "   < <   endl;
        }
};

class   CMath:   public   CBase
{
public:
        CMath(){};
        ~CMath(){};

        void   BaseMethod()
        {
              cout   < <   "BaseMethod   in   Math "   < <   endl;
        }
};

CBase和CMath都实现了BaseMethod().

CTest <CBase>   *pTest   =   new   CTest <CBase> ;
pTest-> BaseMethod();   ---->   调用CBase的BaseMethod();

CTest <CMath>   *pTest   =   new   CTest <CMath> ;
pTest-> BaseMethod();   ---->   调用CMath的BaseMethod();

由此可见,利用模版技术实现多态,就需要通过类似
template <class   T>
class   CTest:public   T
{
...
}

这样的模版类.

这种类起初看起来怪怪的,但很关键.

抱歉!评论已关闭.