C++基础|拷贝构造代码实践

String类

#include <iostream>
using namespace std;

class String 
{
public:
	String(const char *str=nullptr)   //处理字符串时,不管传进来的字符串是否为空,都给底层字符串开辟空间,避免之后所有的操作都要对字符串进行判空
	{
		if (str != nullptr)
		{
			m_str = new char[strlen(str) + 1];
			strcpy(this->m_str, str);
		}
		else
		{
			m_str = new char[1];
			*m_str = '\0';
		}
	}
	String(const String &src)
	{
		m_str =new char[strlen( src.m_str)+1];
		strcpy(m_str, src.m_str);
	}
	
	~String()
	{
		delete[]m_str;
		m_str = nullptr;
	}
	String & operator=(const String &other)  //赋值重载函数
	{
		if (this == &other)
		{
			return *this;
		}
		delete[]m_str;

		m_str = new char[strlen(other.m_str) + 1];
		strcpy(m_str, other.m_str);
		return *this;

	}

private:
	char *m_str;
};

int main()
{
	//调用带参的构造函数
	String s1;
	String s2("hello");
	String s3 = "world";

	//调用拷贝构造函数
	String s4(s3);
	String s5 = s3;

	//调用赋值重载阿函数
	s1 = s2;

	return 0;
}

循环队列

#include <iostream>
using namespace std;
class Queue
{
public:
	Queue(int size = 5)
	{
		_pQue = new int[size];
		_front = _rear = 0;
		_size = size;
	}
	~Queue()
	{
		delete[]_pQue;
		_pQue = nullptr;
	}

   void push(int val)//队尾入队
	{
		if (full())
			resize();
		_pQue[_rear] = val;
		_rear = (_rear + 1) % _size;		
	}

	void pop()
	{
		if (empty())
			return;
		_front = (_front + 1) % _size;
	}
	int front()
	{
		return _pQue[_front];
	}
	bool full()
	{
		return (_rear + 1) % _size == _front;
	}
	bool empty()
	{
		return _front == _rear;
	}

private:
	int *_pQue;   //申请队列的数组空间
	int _front;   //指示队头
	int _rear;     //指示队尾
	int _size;

	void resize()
	{
		int *ptmp = new int[2 * _size];
		int index = 0;
		for (int i= _front; i != _rear; i = (i + 1) % _size)
		{
			ptmp[index++] = _pQue[i];
		}
		delete[]_pQue;
		_pQue = ptmp;
		_front = 0;
		_rear = index;
		_size *= 2;
	}

};

int main()
{
	Queue queue;
	for (int i = 0; i < 20; ++i)
	{
		queue.push(rand() % 100);
	}
	while (!queue.empty())
	{
		cout << queue.front() << " ";
		queue.pop();
	}
	cout << endl;
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值