zoukankan      html  css  js  c++  java
  • 类String的构造函数、析构函数和赋值函数

    一、类String的原型为:

     1 class String
     2 {
     3 public:
     4     String(const char *str = NULL);             //普通构造函数
     5 
     6     ~String(void);                              //析构函数
     7 
     8     String(const String &other);                //拷贝构造函数
     9 
    10     String & operator=(const String & other);   //赋值函数
    11 
    12 private:
    13     char *m_pData;
    14 };

    二、类String的普通构造函数

     1 String::String(const char *str)
     2 {
     3     if(str == NULL)
     4     {
     5         m_pData  = new char[1];
     6         *m_pData = '\0';
     7     }
     8     else
     9     {
    10         int length = strlen(str);
    11         m_pData = new char[length + 1];
    12         strcpy(m_pData, str);
    13     }
    14 }

    三、类String的析构函数

    1 String::~String(void)
    2 {
    3     //由于m_pData是内部数据类型,也可以写成 delete m_pData;
    4     delete [] m_pData;
    5 }

    四、类String的拷贝构造函数

    1 String::String(const String &other)
    2 {
    3     int length = strlen(other.m_pData);
    4     
    5     m_pData = new char[length + 1];
    6     
    7     strcpy(m_pData, other.m_pData);
    8 }

    五、类String的赋值函数

     1 String & String::operator=(const String &other)
     2 {
     3     if(this == &other)                   //检查自赋值
     4         return *this;
     5 
     6     delete [] m_pData;                   //释放原来的资源
     7 
     8     int length = strlen(other.m_pData);  //分配新的资源并分配控件
     9     m_pData = new char[length + 1];
    10     strcpy(m_pData, other.m_pData);
    11 
    12     return *this;                        //返回自身的引用
    13 }
  • 相关阅读:
    十一周总结
    第十周课程总结
    第九周课程总结&实验报告
    第八周课程总结&实验报告
    第七周&实验报告五
    第六周&Java实验报告四
    课程总结
    第十四周课程总结
    第十三周总结
    十二周课程总结
  • 原文地址:https://www.cnblogs.com/Dreamcaihao/p/3091662.html
Copyright © 2011-2022 走看看