C++ —— 三大函数(big three):拷贝构造,拷贝赋值,析构函数

C++三大函数:

  • 拷贝构造函数
  • 拷贝赋值函数
  • 析构函数

设计一个CMyString类,实现上述三大函数,手撕代码如下:

#pragma once
#pragma warning(disable:4996)
#include <iostream>
#include <cstring>


class CMyString
{
public:
	CMyString(const char* pStr);
	CMyString(const CMyString& str);
	CMyString& operator = (const CMyString& str);
	~CMyString();

public:
	char* GetData() const;

private:
	char* m_pData;
};



//构造
//默认构造
CMyString::CMyString(const char* pStr):m_pData(NULL)
{
	if (pStr)
	{
		m_pData = new char[strlen(pStr) + 1];
		//std::cout << "len: " << strlen(pStr) << std::endl;
		strcpy(m_pData, pStr);
	}
	else
	{
		m_pData = new char[1];
		*m_pData = '\0';
	}
}

//拷贝构造
CMyString::CMyString(const CMyString& str)
{
	m_pData = new char[strlen(str.GetData()) + 1];
	strcpy(m_pData, str.GetData());
}

//拷贝赋值 重载=操作符
CMyString& CMyString::operator=(const CMyString& str)
{
	if (str.GetData() == m_pData)
	{
		return *this;
	}
	else
	{
		delete[] m_pData;
		m_pData = new char[strlen(str.GetData()) + 1];
		strcpy(m_pData, str.GetData());
		return *this;
	}
}

//析构
CMyString::~CMyString()
{
	if (m_pData)
	{
		delete[] m_pData;
		m_pData = NULL;
	}
}

//实现
char* CMyString::GetData() const
{
	return m_pData;
}

//测试例代码

#include "CMyString.h"
#include <stdlib.h>


int main()
{

//big three
	CMyString s1("helloxw");
	std::cout << "s1: " <<s1.GetData()<<std::endl;

	CMyString s2(s1);
	std::cout << "s2: " << s2.GetData() << std::endl;

	CMyString s3 = s2;
	std::cout << "s3: " << s3.GetData() << std::endl;

	CMyString s4 = "world";
	std::cout << "s4: " << s4.GetData() << std::endl;

	s1 = s4;
	std::cout << "拷贝赋值后的s1: " << s1.GetData() << std::endl;
	
}

//运行结果截图:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xw-何妨吟啸且徐行

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

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

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

打赏作者

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

抵扣说明:

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

余额充值