2019年3月6日 星期三

c++ 自訂一個操作字串的類型

// 自訂一個操作字串的類型  str.c
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
template<class T>
class superBuffer   {
    private:// hide member, invisible for any other class except friend class
        unsigned msize;     // length to allocate
        T*          address;// pointer to the buffer
    public:    // public for everyone
        const unsigned &length = msize;  // length is read only for public access, it's alias of msize
        T*    const    &array  = address;// array (not *array) is read only, it's alias of address
        ~superBuffer()              { if (address != nullptr) delete [ ] address; }
        superBuffer(unsigned len){ msize = len; address = new T [msize+1]; } // 1 more space to fill EOS
 };
class strBuffer: public superBuffer<char> {
    public:
        unsigned size; // # of char in-use
        void  flush()                            {size = 0; array[0] = 0;}
        strBuffer(int len): superBuffer(len)    {flush() ;              }
        strBuffer & operator ~ (void)           {flush() ; return *this;}
        strBuffer & operator - (unsigned len)   {if (size >= len) size -= len; array[size]=0; return *this;}   
        strBuffer & operator + (const char *src){ return (*this)(src); }
        strBuffer & operator + (strBuffer &msg) { return (*this)(msg.array); }
        strBuffer & operator ()(const char *fmt,...){
            va_list  args;
            va_start(args, fmt);
            size += vsprintf(array + size, fmt, args);
            va_end(args);   
            return *this;
          }
         strBuffer & dump(){
             printf("%s\n", array);
             return *this;
         }
 };
 int main( ) {
     auto str = strBuffer(100); // 產生一個字串, 長度 100 的物件
     (str + ", append a string\n" ).dump(); // 用符號 + 加入字串
     (~str)("del previous string\n").dump();// 用符號 ~ 刪除前面字串
     str("append formated string :%d\n", 3).dump(); // 用雙小括號加入格式化字串
}
需要注意 ( ) 運算符號優先順序比 ~ 的運算符號優先順序高, 如果要求順序時, 可以用雙小括號將它括起來. 用  g++  str.c && ./a.out 編譯並執行
, append a string

del previous string

del previous string
append formated string :3

沒有留言: