温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-28 11:12:34 来源:脚本之家 阅读:401 作者:爱思考的小鸟 栏目:编程语言

详解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]; //对空字符串自动申请存放结束标志'\0'的空间 
    if (m_data==NULL)
    {//内存是否申请成功 
     std::cout<<"申请内存失败!"<<std::endl; 
     exit(1); 
    } 
    m_data[0]='\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 的构造函数、拷贝构造函数、析构函数和赋值函数的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI