详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数
2019/7/10 22:42:18
本文主要是介绍详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
详解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 的构造函数、拷贝构造函数、析构函数和赋值函数的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
这篇关于详解C++ 编写String 的构造函数、拷贝构造函数、析构函数和赋值函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-04安装 VPrix Desktop 的系统要求-icode9专业技术文章分享
- 2024-05-01巧用 TiCDC Syncpoint 构建银行实时交易和准实时计算一体化架构
- 2024-05-01银行核心背后的落地工程体系丨Oracle - TiDB 数据迁移详解
- 2024-04-26高性能表格工具VTable总体构成-icode9专业技术文章分享
- 2024-04-16软路由代理问题, tg 无法代理问题-icode9专业技术文章分享
- 2024-04-16程序猿用什么锅-icode9专业技术文章分享
- 2024-04-16自建 NAS 的方案-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数, 加上remote_src: yes 配置-icode9专业技术文章分享
- 2024-04-14ansible 检测远程主机的8080端口,如果关闭,则echo 进程已关闭-icode9专业技术文章分享