String类重写
2024-10-13 08:22:18
#include <iostream>
#include<string.h> using namespace std;
class String
{
int length;
int i;
private:
char* m_data;//用于保护字符串
public:
String(const char *str=NULL)//普通构造函数
{
cout<<"调用了构造函数"<<endl;
if(str==NULL)
{
length=;
m_data=new char(); //指针指向这段空间
m_data[]='\0';
}
else
length=strlen(str);
m_data=new char(length+);
strcpy(m_data, str);
} String(const String &other)//拷贝构造函数
{
cout<<"调用了拷贝函数"<<endl; if(m_data)
{
delete []m_data;
int length=strlen(other.m_data);
m_data=new char[length+];
strcpy(m_data, other.m_data);
}
} ~String(void)//析构函数
{
cout<<"调用了析构函数"<<endl;
if (m_data) {
delete []m_data;
}
}
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+];
strcpy(m_data, other.m_data);
return *this;
} }; int main()
{
String str("abc");
String str1(str);
str.operator=(str);
}
最新文章
- Android环境变量配置
- Makefile中静态库,动态库的创建和使用以及解压缩命令
- JSP-JSTL学习
- Thinkphp 边学边用-验证码无意间犯的错
- ThinkPHP 购物商城网站(数据库中增删改查的功能实现)——————重点——————
- MySQL 命令行导出、导入Select 查询结果
- poj1992 数论
- Intro to Filtering with Network Monitor 3.0
- DzzOffice1.0 Beta2 全新安装图文教程及界面简单了解
- github/hexo搭建个人博客几个问题总结
- NOIP2014 寻找道路
- chmod 命令
- Struts2返回Json数据(使用Struts2插件)
- python_批量修改文件名
- OC工程调用Swift方法
- [Postman]创建第一个集合(2)
- vue-vuex状态管理-1
- 【Java入门提高篇】Day23 Java容器类详解(六)HashMap源码分析(中)
- 如何判断使用的是Lodop还是C-Lodop
- UVALive - 6442 (思维题)