image.png
    PPT:
    image.png
    image.png
    image.png
    image.png
    image.png
    代码:
    image.png

    1. #ifndef SMARTPOINTER_H
    2. #define SMARTPOINTER_H
    3. namespace DJLib
    4. {
    5. template <typename T>
    6. class smartPointer{
    7. protected:
    8. T* m_pointer;
    9. public:
    10. smartPointer(T* p = NULL)
    11. {
    12. m_pointer = p;
    13. }
    14. //拷贝构造函数与赋值操作符重载来实现一片堆空间只能由一个指针标识
    15. smartPointer(const smartPointer<T>& obj)//拷贝构造函数
    16. {
    17. m_pointer = obj.m_pointer;//当前对象的指针指向参数对象指向的堆空间
    18. const_cast<smartPointer<T>&>(obj).m_pointer = NULL;//参数对象指空(强制类型转换:去除const属性)
    19. }
    20. smartPointer<T>& operator = (const smartPointer<T>& obj)//赋值操作符重载
    21. {
    22. if(this != &obj)//不能自赋值
    23. {
    24. delete m_pointer;
    25. m_pointer = obj.m_pointer;
    26. const_cast<smartPointer<T>&>(obj).m_pointer = NULL;
    27. }
    28. return *this;//支持连续赋值
    29. }
    30. T* operator -> ()
    31. {
    32. return m_pointer;
    33. }
    34. T& operator * ()
    35. {
    36. return *m_pointer;
    37. }
    38. bool isNull()
    39. {
    40. return (m_pointer == NULL );
    41. }
    42. T* get()
    43. {
    44. return m_pointer;
    45. }
    46. ~smartPointer()
    47. {
    48. delete m_pointer;
    49. }
    50. };
    51. }
    52. #endif // SMARTPOINTER_H

    image.png

    1. #include <iostream>
    2. #include "smartpointer.h"
    3. using namespace std;
    4. using namespace DJLib;
    5. class Test
    6. {
    7. public:
    8. Test()
    9. {
    10. cout<< "Test" << endl;
    11. }
    12. ~Test()
    13. {
    14. cout<< "~Test" << endl;
    15. }
    16. };
    17. int main()
    18. {
    19. smartPointer<Test> sp = new Test();
    20. smartPointer<Test> nsp ;
    21. nsp = sp;
    22. cout << sp.isNull() <<endl;
    23. cout << nsp.isNull() <<endl;
    24. return 0;
    25. }