Xây dựng 1 lớp biểu diễn xâu kí tự có các hàm tạo và hảm hủy cần thiết

Xây dựng 1 lớp biểu diễn xâu kí tự có các hàm tạo và hảm hủy cần thiết. Viết hàm thành phần concat() để nối xâu đối tượng với một xâu khác và hàm in nội dung của xâu ra màn hình.

/************************************************************
* Author: VNCODING
* History                  
* 2016/03/21        first create    VNCODING
*************************************************************/

#include <iostream>
#include <string.h>

using namespace std;

class CString
{
private:
    char* m_str; 
public:
    CString(char* s = NULL)
    {
        if(s == 0)
        {
            m_str = _strdup("");
        }
        else
        {
            m_str = _strdup(s);
        }
    }
    ~CString()
    {
        if(m_str != NULL)
            delete [] m_str;
    }
    // Assign operator
    CString& operator=  (const CString& s)
    {
        // delete old content
        delete this->m_str;
        this->m_str = strdup(s.m_str);
        return *this;
    }

    // Concentrate operator
    CString& operator+ (const CString& s)
    {
        char* nStr = new char[strlen(s.m_str) + strlen(this->m_str) + 1];
        strcpy(nStr, this->m_str);
        strcat(nStr, s.m_str);
        delete this->m_str;
        this->m_str = nStr;
        return *this;
    }


    void print(){ cout << this->m_str << endl;}
};

void main()
{
    CString str1 = "vncoding";
    CString str2 = ".net";
    str1.print();
    CString str = str1 + str2;
    str1.print();
    str.print();
    system("pause");
}

Chú ý: ở đây đối tượng str1 đóng vai trò con trỏ this trong chồng toán tử operator+

Kết quả:

Xây dựng 1 lớp biểu diễn xâu kí tự
Xây dựng 1 lớp biểu diễn xâu kí tự

Be the first to comment

Leave a Reply