温馨提示×

温馨提示×

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

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

怎么使用C++实现String类

发布时间:2021-04-14 11:01:45 来源:亿速云 阅读:207 作者:小新 栏目:编程语言

小编给大家分享一下怎么使用C++实现String类,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

C++实现String类实例代码

这是一道十分经典的面试题,可以短时间内考查学生对C++的掌握是否全面,答案要包括C++类的多数知识,保证编写的String类可以完成赋值、拷贝、定义变量等功能。

#include<iostream>  using namespace std;    class String  {  public:      String(const char *str=NULL);      String(const String &other);      ~String(void);      String &operator =(const String &other);  private:      char *m_data;  };    String::String(const char *str)  {    cout<<"构造函数被调用了"<<endl;    if(str==NULL)//避免出现野指针,如String b;如果没有这句话,就会出现野           //指针    {      m_data=new char[1];      *m_data=''/0'';    }    else    {     int length=strlen(str);     m_data=new char[length+1];     strcpy(m_data,str);    }  }  String::~String(void)  {    delete m_data;    cout<<"析构函数被调用了"<<endl;  }    String::String(const String &other)  {   cout<<"赋值构造函被调用了"<<endl;   int length=strlen(other.m_data);   m_data=new char[length+1];   strcpy(m_data,other.m_data);  }  String &String::operator=(const String &other)  {     cout<<"赋值函数被调用了"<<endl;     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);//拷贝     return *this;  }  void main()  {     String b;//调用构造函数     String a("Hello");//调用构造函数     String c("World");//调用构造函数     String d=a;//调用赋值构造函数,因为是在d对象建立的过程中用a来初始化     d=c;//调用重载后的赋值函数  }

以上是“怎么使用C++实现String类”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

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

AI