C++实现简单string类

#C++实现简单string类
1、string.h

#pragma once
#ifndef __MYSTRING__
#define __MYSTRING__

#include<iostream>
using namespace std;

//类中带有指针必须有拷贝构造和拷贝赋值,默认的只改变指针指向,造成内存泄漏(浅拷贝)
class String {
public:
	String(const char* cstr = 0);//构造函数
	String(const String& str);//拷贝构造
	String& operator= (const String& str);//拷贝赋值
	~String();//析构

	char* get_c_str() const { return m_data; }
	
private:
	char* m_data;
	friend ostream& operator<<(ostream& os, const String& str);
};

String::String(const char* cstr)
{
	if (cstr)
	{
		m_data = new char[strlen(cstr) + 1];//字符串有一个结束符\0
		strcpy_s(m_data, strlen(cstr) + 1, cstr);
	}
	else
	{
		m_data = new char[1];
		*m_data = '\0';
	}
}

String::~String()
{
	delete[] m_data;
}

String::String(const String& str)//深拷贝
{
	m_data = new char[strlen(str.m_data) + 1];
	strcpy_s(m_data, strlen(str.m_data) + 1, str.m_data);
}
String& String::operator= (const String& str)
{
	if (this == &str)//检查自我赋值
		return *this;
	delete[] m_data;//清除内存
	m_data = new char[strlen(str.m_data) + 1];
	strcpy_s(m_data, strlen(str.m_data) + 1, str.m_data);
	return *this;
}

ostream& operator<<(ostream& os, const String& str)
{
	os << str.get_c_str();
	return os;
}
#endif // !__MYSTRING__

2、测试Mystring.cpp

#include<iostream>
#include"Mystring.h"
using namespace std;
int main()
{
	String s1("hello");
	String s2("world");
	String s3(s1);
	cout << s3 << endl;
	s3 = s2;
	cout << s3 << endl;
	return 0;
}

3、实验结果
在这里插入图片描述
注意:
1、字符串复制时,利用strcp_s取代strcpy,解决error问题,主要是unsafe的问题。
2、new的内部操作分三步:

例如complex类
Complex* pc=new Complex(1,2);
转化为:
Complex *pc;
1void* mem=operator new(sizeof(Complex)); //分配内存,底层调用malloc
2、pc=static_cast<Complex*>(mem);//类型强制转换
3、pc->Complex::Complex(1,2);//调用构造函数

delete的内部操作先调用析构函数,后释放内存free

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dailingGuo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值