字符串类的构造函数,拷贝构造,赋值函数的实现

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;
}




  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值