zoukankan      html  css  js  c++  java
  • 封装字符串的Format操作

    相信即使再讨厌MFC的朋友也不会把厌恶牵扯到CString类上,
    而且CString现在也提升为ATL和MFC的共享类。用CString类,
    当然不能忘记它的Format方法,其用于格式化字符串。示例操作如下:
    CString  strDemo;
    strDemo.Format( _T("数字为:%d, 字符串为:%s"), 1, strOther );

    很简单的使用.但我总觉得用的太多代码不美观(或许我有点洁癖吧),我总觉得一行代码
    的事用两行代码有点多余,于是我封装了StringFormatEx类.该类的封装风格借鉴了
    ATL的字符串转换类的风格(如CA2TEX、CT2WEX等),
    代码如下:
    /*
    * 格式化字符串
    */
    template
    < int t_nBufferLength = 128 >
    class StringFormatEx
    {
    public:
        StringFormatEx( PCTSTR pszFormat, ) 
    throw()
        {
            va_list ptr; 
            va_start(ptr, pszFormat);

            CString strFormat;
            strFormat.FormatV( pszFormat, ptr );

            ASSERT( t_nBufferLength 
    > strFormat.GetLength() );

            _stprintf_s( m_szBuffer, strFormat );

            va_end(ptr);
        }

        
    operator LPCTSTR() throw()
        {
            
    return (m_szBuffer);
        }

    private:
        TCHAR m_szBuffer[t_nBufferLength];

    private:
        StringFormatEx( 
    const StringFormatEx& ) throw();
        StringFormatEx
    & operator=const StringFormatEx& ) throw();
    };

    typedef StringFormatEx
    <> StringFormat;

    使用示例:

    //void Test( LPCTSTR lpsz ){}

    Test( StringFormat( _T("数字为:%d, 字符串为:%s"), 1, strOther  ) );

  • 相关阅读:
    手工创建数据库的全部脚本及说明(转)
    HNOI 2009 梦幻布丁 链表 启发式合并
    【除草】【hnoi】精简题解
    矩阵乘法
    忧桑啊。。。
    【水】【SCOI】 精简题解
    [数论][SDOI2012]Longge的问题
    【2013】省选
    【集训队互测】ayq 三道题
    【水】 【SDOI】 极精简题解
  • 原文地址:https://www.cnblogs.com/fangkm/p/1426532.html
Copyright © 2011-2022 走看看