类的构造函数,析构函数,赋值函数

// 提示strcpy安全问题,解决方法
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <stdint.h>
using namespace std;

class MyClass
{
public:
	MyClass();
	~MyClass();
	void foo(){cout << "A" << endl;}
private:

};

MyClass::MyClass()
{
}

inline MyClass::~MyClass()// 析构函数可以是内联函数
{
	cout << "inline destructed." << endl;
}

class StringT
{
public:
	StringT(const char *str = NULL);           // 普通构造函数
	StringT(const StringT &other);             // 拷贝构造函数
	StringT & operator=(const StringT &other); // 赋值函数
	void Print(const StringT &other) const;    // const成员函数
	~StringT(void);                            // 析构函数

private:
	char *m_pdata;
};

StringT::~StringT(void)
{
	delete m_pdata;
}

void StringT::Print(const StringT &other) const
{
	int len = strlen(other.m_pdata);
	char *p = other.m_pdata;
	for (int i = 0; i < len; i++)
	{
		cout << *(p++);
	}
	cout << endl;
}

StringT::StringT(const char *str)
{
	if (str == NULL)
	{
		m_pdata = new char[1];
		*m_pdata = '\0';
	} 
	else
	{
		int length = strlen(str);
		m_pdata = new char[length + 1];
		strcpy(m_pdata,str);
	}
}
StringT::StringT(const StringT & other)
{
	if (other.m_pdata == NULL)
	{
		m_pdata = new char[1];
		*m_pdata = '\0';
	} 
	else
	{
		int length = strlen(other.m_pdata);
		m_pdata = new char[length + 1];
		strcpy(m_pdata,other.m_pdata);
	}
}
//赋值函数实现方法①
StringT& StringT::operator =(const StringT &other)
{
	// 1检测是否自身赋值
	if (this == &other)
	{
		return *this;
	}
	// 2释放原有内存资源
	delete m_pdata;

	// 3重新分配内存资源,并赋值other中内容
	int length = strlen(other.m_pdata);
	m_pdata = new char[length + 1];
	strcpy(m_pdata, other.m_pdata);
	return *this;
}
//赋值函数实现方法② 源自剑指offer面试例题1
//StringT& StringT::operator =(const StringT &other)
//{
//	if (this != &other)
//	{
//		StringT strTmp(other);
//		char *pTmp = strTmp.m_pdata;
//		strTmp.m_pdata = m_pdata;
//		m_pdata = pTmp;
//	}
//	return *this;
//}
int main()
{
	MyClass *P = new MyClass();
	P->foo();
	delete P;

	StringT str("hello");
	StringT s(str);
	StringT t = s;

	cout << "str = ";
	str.Print(str);

	cout << "s = ";
	s.Print(s);

	cout << "t = ";
	t.Print(t);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Digital2Slave

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

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

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

打赏作者

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

抵扣说明:

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

余额充值