加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > 正文

详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值

发布时间:2020-12-25 04:34:18 所属栏目:创业 来源:网络整理
导读:详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数 编写类String 的构造函数、析构函数和赋值函数,已知类String 的原型为: class String{public:String(const char *str = NULL); // 普通构造函数String(const String // 拷贝构造函数~ St

详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数

 编写类String 的构造函数、析构函数和赋值函数,已知类String 的原型为:

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

#include <iostream> 
class String 
{ 
public: 
  String(const char *str=NULL);//普通构造函数 
  String(const String &str);//拷贝构造函数 
  String & operator =(const String &str);//赋值函数 
  ~String();//析构函数 
protected: 
private: 
  char* m_data;//用于保存字符串 
}; 
 
//普通构造函数 
String::String(const char *str)
{ 
  if (str==NULL)
  { 
    m_data=new char[1]; //对空字符串自动申请存放结束标志''的空间 
    if (m_data==NULL)
    {//内存是否申请成功 
     std::cout<<"申请内存失败!"<<std::endl; 
     exit(1); 
    } 
    m_data[0]=''; 
  } 
  else
  { 
    int length=strlen(str); 
    m_data=new char[length+1]; 
    if (m_data==NULL)
    {//内存是否申请成功 
      std::cout<<"申请内存失败!"<<std::endl; 
      exit(1); 
    } 
    strcpy(m_data,str); 
  } 
} 

//拷贝构造函数 
String::String(const String &other)
{ //输入参数为const型 
  int length=strlen(other.m_data); 
  m_data=new char[length+1]; 
  if (m_data==NULL)
  {//内存是否申请成功 
    std::cout<<"申请内存失败!"<<std::endl; 
    exit(1); 
  } 
  strcpy(m_data,other.m_data); 
} 

//赋值函数 
String& String::operator =(const String &other)
{//输入参数为const型 
  if (this == &other) //检查自赋值 
  { return *this; }

  delete [] m_data;//释放原来的内存资源 

  int length=strlen(other.m_data);   
  m_data= new char[length+1]; 
  if (m_data==NULL)
  {//内存是否申请成功 
    std::cout<<"申请内存失败!"<<std::endl; 
    exit(1); 
  } 
  strcpy(m_data,other.m_data); 

  return *this;//返回本对象的引用 
} 

//析构函数 
String::~String()
{ 
  delete [] m_data; 
} 
 
void main()
{ 
  String a; 
  String b("abc"); 
  system("pause"); 
} 

以上就是C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读