一、string類簡單實現
String類簡單實現:
class String
{
public:
String(const char *str = nullptr)//構造函數
{
if (str != nullptr)
{
m_data = new char[strlen(str) + 1];
strcpy(m_data, str);
}
else
{
m_data = new char[1];//保證String對象一定是一個有效對象
*m_data = '\0';
}
}
String(const String &other)//拷貝構造函數
{
//m_data = other.m_data;默認構造
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
}
~String(void)//析構函數
{
delete[]m_data;
m_data = nullptr;
}
//String&是爲了支持連續的operator=賦值操作
String& operator= (const String &other)//賦值運算符重載函數
{
if (this == &other)
{
return *this;
}
delete[]m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data, other.m_data);
return *this;
}
private:
char *m_data;//用於保存字符串
};
int main()
{
//調用默認構造
String str1;
String str2("hello");
String str3 = "world";
//調用拷貝構造函數
String str4 = str3;
String str5(str3);
//調用賦值運算符重載函數
str3 = str1 = str2;
//賦值從右往左賦
//str1 = str2;
//str1.operator=(str2); =>返回值類型若用void則不行
//str3 = void;//應該用str1賦給str3 str3 = str1;
//因此返回值爲當前類型引用是爲支持連續賦值
return 0;
}
二、循環隊列實現
循環隊列簡單實現:
class Queue
{
public:
Queue(int size = 5)//構造
{
_pQue = new int[size];
_front = _rear = 0;
_size = size;
}
//Queue(const Queue&) = delete;刪除拷貝構造
//Queue& operator= (const Queue&) = delete;刪除賦值運算符重載
Queue(const Queue &src)//拷貝構造
{
_size = src._size;
_front = src._front;
_rear = src._rear;
_pQue = new int[_size];
for (int i=_front; i!=_rear; i=(i+1)%_size)
{
_pQue[i] = src._pQue[i];
}
}
Queue& operator= (const Queue &src)//賦值運算符重載
{
if (this == &src)
{
return *this;
}
delete[]_pQue;
_size = src._size;
_front = src._front;
_rear = src._rear;
_pQue = new int[_size];
for (int i=_front; i!=_rear; i=(i+1)%_size)
{
_pQue[i] = src._pQue[i];
}
return *this;
}
~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;
}
void resize()
{
int *ptmp = new int[2 * _size];
//擴容後需從fornt遍歷到rear,元素需要從新內存的第0號位元素開始放
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;
}
private:
int *_pQue;//申請隊列的數組空間
int _front;//隊頭
int _rear;//隊尾
int _size;//隊列擴容的總大小
};
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;
Queue queue1 = queue;
queue1 = queue;
return 0;
}
測試一下:測試成功