类和对象代码应用实践

1. string类型

20250302173610

string的成员变量为指针,因此拷贝构造函数和赋值运算符重载函数都得重写。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class String
{
public:
String(const char *str = nullptr) //普通的构造函数
{
if (str != nullptr)
{
m_data = new char[strlen(str) + 1]; //需要额外的1个字节来存储字符串的终止符 \0
strcpy(m_data, str); //strcpy 逐字符地从源字符串复制到目标字符串,直到遇到终止符 \0(空字符)为止
}
else //空字符串
{
m_data=new char[1];
*m_data='\0';
}
}
String(const String &other) //拷贝构造函数,参数为const,防止原对象被修改
{
m_data=new char[strlen(other.m_data)+1];//根据参数字符串的长度分配内存
strcpy(m_data,other.m_data);
}
String &operator=(const String &str) //赋值运算符重载函数,返回值类型为string&是为了连续赋值
{
if(this==&str) return *this;
delete[] m_data;
m_data=new char[strlen(other.m_data)+1];//根据参数字符串的长度分配内存
strcpy(m_data,other.m_data);
return *this;
}
~String() //析构函数
{
delete[] m_data;
m_data=nullptr;
}

private:
char *m_data;




}
int main()
{
//调用构造函数
String str1("hello world");
String str3;
//调用拷贝构造函数
String str2=str1;
//调用赋值运算符重载函数,从右往左
str3=str1=str2;
}

2. 循环队列 Queue

class Queue
{
public:
Queue(int size = 20) //构造函数
{
_pQue = new int[size];
_front = _rear = 0;
_size = size;

}
~Queue()   //析构函数
{
    delete[] _pQue;
    _pQue = nullptr;
}
void addQue(int val)
{
    if(full())
    {
        resize();
    }
    else
    {
        _pQue[_rear] = val;
        _rear = (_rear + 1) % _size;
    }
}
void pop()
{
    if(empty())
    {
        return;
    }
    _front = (_front + 1) % _size;

}
int top()   //获取队头元素
{
    return _pQue[_front];
}
bool empty()   //判断队列是否为空
{
    return _front == _rear;
}
bool full()   //判断队列是否为满
{
    return (_rear + 1) % _size == _front;
}
Queue(const Queue &src) //拷贝构造函数
{
    _size=src._size;
    _pQue = new int[src._size];
    for(int i=_front ;i!=rear;i=(i+1)%_size)
    {
        _pQue[i]=src._pQue[i];
    }
    _front=src._front;
    _rear=src._rear;


}
Queue &operator=(const Queue &src)   //赋值运算符重载函数
{
    if(this==&src) return *this;
    delete[] _pQue;
    _size=src._size;
    _pQue = new int[src._size];
    for(int i=_front ;i!=rear;i=(i+1)%_size)
    {
        _pQue[i]=src._pQue[i];
    }
    _front=src._front;
    _rear=src._rear;
    return *this;

}

private:
int _pQue; //申请队列的数组空间,浅拷贝有问题,需要自己实现拷贝构造与赋值
int _front;
int _rear;
int _size;
void resize() //扩容
{
int index = 0;
int
pNew = new int[_size 2];
for(int i=_front;i!=_rear;i=(i+1)%_size)
{
pNew[index++] = _pQue[i];
}
delete[] _pQue;
_pQue = pNew;
_front = 0;
_rear = index;
_size
= 2;
}

}