String构造函数 拷贝构造函数 析构函数 赋值构造函数的实现

本文详细介绍了C++中自定义字符串类MyString的构造函数、拷贝构造函数、析构函数和赋值函数的实现,旨在帮助读者理解如何在C++中高效地操作字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标题:String函数的实现-->主要实现构造函数,拷贝构造函数,析构函数,赋值构造函数。这几个函数是字符串函数最基本的函数,今天也总结一下
#include<iostream>
using namespace std;
#include<string.h>

class MyString
{
private:
	char *str;
public:
	MyString(const char *pStr)//构造函数
	{
		if(pStr==NULL)
		{
			str=new char[1];
			*str='\0';
		}
		else
		{
			str=new char[strlen(pStr)+1];
			strcpy(str,pStr);
		}
	}
	MyString(const MyString &other)//拷贝构造函数,必须用引用传递,
								//如果不用引用传递将会出现无限递归循环
	{
		if(this==&other)
			return;
		str=new char[strlen(other.str)+1];
		strcpy(str,other.str);
	}
	~MyString()//析构函数
	{
		delete []str;
		str=NULL;//防止野指针
	}
	//最简单直接的写法(赋值函数)用引用返回为了连续赋值
	/*MyString& operator=(const MyString &other)
	{
		if(this != &other)
		{
			delete []str;
			str=new char[strlen(other.str)+1];
			strcpy(str,other.str);
		}
		return *this;
	}*/
	//高级程序员的写法(赋值函数)
	MyString& operator=(const MyString &other)
	{
		if(this != &other)
		{
			MyString Tmp(other);//交换指向的地址,然后退出if语句后自动调用析构函数释放之前的内存
			char *ret=Tmp.str;
			Tmp.str=str;
			str=ret;
		}
		return *this;//返回*this
	}
	void show()const
	{
		cout<<"str="<<str<<endl;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值