字符串類的構造函數,拷貝構造,賦值函數的實現

1.MyString.h

//MyString.h

#pragma once

class String
{
 public:
     String(const char *str = NULL);//普通構造函數
     String(const String &other);//拷貝構造函數
    ~String(void);//析構函數
     String & operator = (const String &other);//賦值函數
private:
    char *m_data;//用來保存字符串
 };

2.MyString.cpp

#include "stdafx.h"
#include <string.h>
#include "MyString.h"

  /*

  *普通構造函數

  *構造函數首先根據一個字符串常量創建一個String對象。

  *這個構造函數首先分配了足夠的內存,然後把這個字符串常量複製到這塊內存

  */
 String::String(const char *str)
 {
     if (str == NULL)
  {
         m_data = new char[1];
         *m_data = '\0';
     }
  else
  {
        int length = strlen(str);
        m_data = new char[length + 1];
        //strcpy(m_data, str);
  strcpy_s(m_data,length+1,str);
     }
 }


 /*

  *拷貝構造函數

  *所有需要分配系統資源的用戶定義類型都需要一個拷貝構造函數

  *它可以在函數調用中以傳值得方式傳遞一個String類型的參數

  *並且在當一個函數以值得形式返回String對象時實現“返回時複製”

  */
 String::String(const String &other)
 {
     int length = strlen(other.m_data);
     m_data = new char[length + 1];
     //strcpy(m_data, other.m_data);
  strcpy_s(m_data, length+1,other.m_data);
 }

 /*
  *定義析構函數是爲了方式內存泄露,當一個String對象超出

  *它的作用域時,析構函數就會釋放它所佔用的內存

 */
 String::~String(void)
 {
    delete[] m_data;//m_data是內部數據類型,也可以寫作delete m_data
 }

 /*
  *賦值函數實現字符串的傳值活動
  */
 String & String::operator = (const String &other)
 {
     if (this == &other)//檢查自賦值
         return *this;

     delete[] m_data;
     int length = strlen(other.m_data);//分配新的內存資源並複製其內容
     m_data = new char[length + 1];
     //strcpy(m_data, other.m_data);
  strcpy_s(m_data,length+1,other.m_data);
     return *this;//返回本對象的引用
 }

3.測試代碼


#include "stdafx.h"
#include "MyString.h"

int _tmain(int argc, _TCHAR* argv[])
{
 String MyString("My first String test!!!");//普通構造函數
   
 String MyString2;//普通構造函數

 String MyString3 = MyString;//拷貝構造函數
   
 MyString2 = MyString;//賦值函數

 return 0;
}




發佈了14 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章