编写类String的构造函数、拷贝构造函数、析构函数和赋值函数

class String
{
public:
    String(const char *str = NULL); // 普通构造函数    
    String(const String &other);    // 拷贝构造函数
    ~String(void);                    // 析构函数    
    String & operator = (const String &other);    // 赋值函数
private:
    char *m_data;                    // 用于保存字符串
};

1、构造函数 

/* 

   1、构造函数在构造对象时使用;
   2、传入参数的判断;
   3、对象的初始化问题。
*/

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

2、拷贝构造函数                                   

/*
   1、拷贝构造函数必须在构造对象时使用,即定义对象时;
   2、对象初始化问题。

*/

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

3、赋值函数                                       

/*
   1、赋值函数使用时,对象肯定已经建立;
   2、赋值前,判断是否是自我赋值;
   3、赋值前,内存空间的准备:
       由于赋值前,对象已占有一定大小内存,但是赋值对象所占内存大小与
       对象已占的内存大小不一定一致;
       先释放对象已占的内存,然后分配心内存。
   4、正常赋值
*/

String & String::operator = (const String &other)
{
    if (&other == this)
    {
        return *this;
    }
    
    delete [] m_data;
    int len = strlen(other.m_data);
    m_data = new char[len+1];
    strcpy(m_data,other.m_data);
    
    return *this;
}

4、析构函数                                        

/*
   资源的释放
*/

String::~String(void)
{
    delete []m_data;
}

 5、拷贝构造函数与赋值函数相关知识             

  1、  拷贝构造函数与赋值函数的区别?

    在看到“=”操作符为对象赋值的时候,

            如果是在对象定义时(Test B = (Test)c),此时调用拷贝构造函数;

            如果不是在对象定义赋值时(B = c),此时调用赋值函数。

    注:构造函数、拷贝构造函数,带有构造两个字,顾名思义,就是在对象声明或定义时才会使用。

  2、拷贝构造函数与赋值函数定义的区别?

    内存空间角度:

      1)拷贝构造函数的使用,是在建立对象时;当时对象没有占有内存,故不需要释放内存,不重新建立内存空间。

      2)赋值函数的使用,是在对象建立后;当时对象已经占有内存,故需要释放先前内存,然后重新获取内存空间。

猜你喜欢

转载自blog.csdn.net/qian27enjoy/article/details/82822750