使用Imp模式避免c++中的改类成员数据导致大规模重新编译

c++的header file+source file的分割有一个不干脆的地方:header file既是一个declaration,也是类数据结构的定义。如果是简单的c with class那没问题,因为struct的结构也是一种declaration。而到了c++,我们还需要封装,所以如果把内部struct暴露给别人就有问题了,抛开设计上的问题还有便以上的不方便:每次改了类的内部成员(增,删,改类型)后,但凡include过(直接或间接)这个头文件定义的其他地方也都要重新编译,在大项目中一不小心可能把半壁江山都重新编译了。我目前有2种方法来缓解这个问题。

假设一个简单的类定义和实现原版为: 

//A.h

class A

{

    public:

    int API();

    protected:

    int mData;

}

//A.cpp

int A::API()

{

    return mData + 1

}

第一种方法是Imp继承法:把A搞成一个虚接口类,再A.cpp里用一个AImp来继承A 

//A.h

class A

{

public:

    virtual void API();

}

//A.cpp

class AImp

{

public:

    virtual int void API()

    {

        return mData +1;

    }

protected:

    int mData;

}

A* CreateA()

{

    return new AImp();

}

Imp继承

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
自己实现的字符串类 class CMStringImp; class CMstring { public: explicit CMstring(void); ~CMstring(void); CMstring(LPCTSTR lpszstr); CMstring(const CMstring& lpszstr); CMstring& operator = (const CMstring& lpszstr); operator LPCTSTR() const; bool operator == (const CMstring&) const; bool operator != (const CMstring&) const; bool operator < (const CMstring&) const; TCHAR operator[] (int nIndex) const; TCHAR& operator[] (int nIndex); CMstring& operator += (LPCTSTR pStr); CMstring& operator += (TCHAR ch); friend CMstring operator+(const CMstring& str1, const CMstring& str2); friend CMstring operator+(const CMstring& str1, LPCTSTR lpszstr); friend CMstring operator+(const CMstring& str1, TCHAR ch); friend CMstring operator+(TCHAR ch, const CMstring& str1); friend CMstring operator+(LPCTSTR lpszstr, const CMstring& str1); // friend wostream operator <<(wostream &is;,const CMstring &str;); public: LPCTSTR GetData() const; bool IsEmpty() const; TCHAR GetAt(int) const; TCHAR& GetAt(int); int GetLength() const; int Compare(const CMstring&) const; int CompareNoCase(const CMstring&) const; int Find(TCHAR ch, int nStart = 0) const; int Find(LPCTSTR pStr, int nStart = 0) const; int ReverseFind(TCHAR ch) const; int ReverseFind(LPCTSTR pStr) const; CMstring Right(int nCount) const; CMstring Left(int nCount ) const; public: CMstring& MakeLower(); CMstring& MakeUpper(); CMstring& MakeReverse(); int Replace(TCHAR chOld, TCHAR chNew); int Replace(LPCTSTR pszOld, LPCTSTR pszNew); int Insert(int iIndex, TCHAR ch); void Format(LPCTSTR lpszFormat, ...); private: CMStringImp* m_pImp; };

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值