码迷,mamicode.com
首页 > 编程语言 > 详细

C++ String 深拷贝(传统写法+现代写法)

时间:2016-03-23 23:49:54      阅读:527      评论:0      收藏:0      [点我收藏+]

标签:c++ string 深拷贝(传统写法+现代写法)

//C++String 类的常规写法
 
#include <iostream>
using namespace std;
class String
{
public:
 //构造函数
 String(char*str = "")              
  :_str(new char[strlen(str) + 1])
 {
  strcpy(_str, str);
 }
 //拷贝构造
 String(const String &s)
 {
  _str = new char[strlen(s._str) + 1];
  strcpy(_str, s._str);
 }
 //operator=的重载
 String&operator=(const String &s)
 {
  if (this != &s)
  {
   /*delete[]_str;
   _str = new char[strlen(s._str) + 1];
   strcpy(_str, s._str);*/
   char*tmp = new char[strlen(s._str) + 1];
   strcpy(tmp, s._str);
   delete[]_str;
   _str = tmp;
   
  }
  return *this;
 }
 //析构函数
 ~String()                         
 {
  if (_str)
  {
   delete[]_str;
  }
 }
 char *CStr()
 {
  return _str;
 }
char& operator[](size_t index)
{
 return _str[index];
}
private:
 char*_str;
};



//C++String类的现代写法

#include <iostream>
using namespace std;
class String
{
public:
 String(char*str="")
  :_str(new char[strlen(str)+1])
 {
  strcpy(_str, str);
 }
 String(const String&s)
  :_str(NULL)
 {
  String tmp(s._str);
  swap(_str, tmp._str);
 }
 String&operator=(const String &s)
 {
  if(this != &s)
  {
   String tmp(s._str);
   swap(_str, tmp._str);
  }
  return *this;
 }
 //对 operator= 优化
 String&operator=(String s)
 {
  swap(_str, s._str);
  return *this;
 }
 ~String()
 {
  if (_str)
  {
   delete[]_str;
  }
 }
 char *CStr()
 {
    return _str;
 }
char& operator[](size_t index)
{
 return _str[index];
}
private:
 char*_str;
};

本文出自 “printf的返回值” 博客,请务必保留此出处http://10741125.blog.51cto.com/10731125/1754454

C++ String 深拷贝(传统写法+现代写法)

标签:c++ string 深拷贝(传统写法+现代写法)

原文地址:http://10741125.blog.51cto.com/10731125/1754454

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!