面试题(44)|数据结构(21):写一个字符串类,熟悉内存管理与拷贝控制

更多C++学习经验,从《C++ Primer》入手学习C++

能够准确无误地编写出String类的构造函数、拷贝构造函数、赋值函数和析构函数的面试者至少已经具备了C++基本功的60%以上!

编写类String的构造函数、析构函数和赋值函数,已知类String的原型为

class MString
{
public:
	MString(const char *str = NULL); // 普通构造函数  
	MString(const MString &other); // 拷贝构造函数  
	~MString(void); // 析构函数  
	MString & operator =(const MString &other); // 赋值函数  
private:
	char *m_data; // 用于保存字符串  
};

实现代码: 

#include "stdafx.h"
#include "MString.h"
#include "string.h"

#pragma warning(disable:4996)

MString::MString(const char* str)
{
	if (str == nullptr)
	{
		// 得分点:对空字符串自动申请存放结束标志'\0'的空
		m_data = new char[1];
		m_data[0] = '\0';
	}
	else {
		int len = strlen(str);
		m_data = new char[len + 1];
		strcpy(m_data, str);
	}
}
MString::~MString()
{
	delete[] m_data;
	m_data = nullptr;
}

// 得分点:输入参数为const型
//拷贝构造函数
MString::MString(const MString &other)
{
	int len = strlen(other.m_data);
	m_data = new char[len + 1];
	strcpy(m_data, other.m_data);
}

//赋值函数
MString& MString::operator=(const MString &other)//得分点,const参数类型
{
	//得分点
	if (this == &other)
	{
		return *this;
	}
	//得分点
	delete[] m_data;
	m_data = nullptr;

	int len = strlen(other.m_data);
	m_data = new char[len + 1];
	strcpy(m_data, other.m_data);
	return *this;
}

当类中包括指针类成员变量时,一定要重载其拷贝构造函数、析构函数和赋值函数,这既是对C++程序员的基本要求,也是《Effective C++》中特别强调的条款。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

haimianjie2012

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

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

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

打赏作者

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

抵扣说明:

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

余额充值