LinkedList.h
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
template <typename T>
class LinkedListNode
{
public:
~LinkedListNode();
T val;
LinkedListNode<T> *p_next;
};
template <typename T>
class LinkedList
{
public:
LinkedList();
~LinkedList();//析构函数,不接收参数
LinkedList(const LinkedList<T>& other);//复制构造函数
LinkedList<T>& operator= (const LinkedList<T>& other);//定义=为深拷贝
void insert(const T &val);//尾插入
void insert_head(const T &val);//头插入
void show_list();
private:
LinkedListNode<T> *_p_head;
LinkedListNode<T> *_p_now;
};
#endif // LINKEDLIST_H_INCLUDED
LinkedList.cpp
#include "LinkedList.h"
using namespace std;
template <typename T>
LinkedListNode<T>::~LinkedListNode()
{
delete p_next;//调用p_next指向对象的析构函数,如果p_next为NULL则什么都不做
}
template <typename T>
LinkedList<T>::LinkedList()
:_p_head(NULL),_p_now(NULL)
{
cout << "调用无参构造函数"<<endl;
};
template <typename T>
LinkedList<T>::~LinkedList()
{
delete _p_head;
}
template <typename T>
LinkedList<T>& LinkedList<T>::operator=(const LinkedList<T>& other)
{
cout << "调用自定义赋值运算"<<endl;
if (this == &other)//this值为本对象地址,是一个指向本对象的指针
return *this;
delete _p_head;//释放原来指向的内存
_p_head = NULL;
LinkedListNode<T> *p_itr = other._p_head;//能访问吗
while (p_itr != NULL){
insert (p_itr->val);
p_itr = p_itr->p_next;
}
return *this;
}
template <typename T>
LinkedList<T>::LinkedList(const LinkedList& other)
:_p_head(NULL)//以防原对象还未初始化,即_p_head不为NULL,但是无效
{
cout << "调用复制构造函数"<<endl;
LinkedListNode<T> *p_itr = other._p_head;
while (p_itr != NULL){
insert (p_itr->val);
p_itr = p_itr->p_next;
}
}
template <typename T>
void LinkedList<T>::insert(const T& val)
{
cout<<_p_head<<endl;
if (_p_head == NULL){
_p_head = new LinkedListNode<T>;
_p_head->val = val;
_p_head->p_next = NULL;
_p_now = _p_head;
}else{
_p_now->p_next = new LinkedListNode<T>;
_p_now->p_next->val = val;
_p_now->p_next->p_next = NULL;
_p_now = _p_now->p_next;
}
}
template <typename T>
void LinkedList<T>::insert_head(const T& val)
{
LinkedListNode<T> *p = _p_head;
_p_head = new LinkedListNode<T>;
_p_head->val = val;
_p_head->p_next = p;
}
template <typename T>
void LinkedList<T>::show_list()
{
LinkedListNode<T> *p = _p_head;
while(p!=_p_now->p_next){
cout<<p->val<<"-->";
p = p->p_next;
}
cout<<"nullptr"<<endl;
}
main.cpp
#include <iostream>
#include "LinkedList.cpp"
using namespace std;
main()
{
LinkedList<int> p_list;//调用无参构造函数
p_list.insert(1);
p_list.insert(2);
p_list.insert(3);
LinkedList<int> p_list2;//调用无参构造函数
p_list2 = p_list; //调用自定义赋值运算
LinkedList<int> p_list3 = p_list;//自动识别,直接调用复制构造函数,不会调用无参构造函数
LinkedList<int> p_list4(p_list);//调用复制构造函数
p_list2.insert(4);
p_list2.insert_head(5);
p_list.show_list();
p_list2.show_list();
p_list3.show_list();
p_list4.show_list();
return 0;
}