C++智能指针

来源:互联网 发布:软件关不掉怎么办 编辑:程序博客网 时间:2024/05/14 10:33
#ifndef _SMART_POINTER_H_#define _SMART_POINTER_H_template <typename T>class SmartPointer{public:SmartPointer();SmartPointer(const T *pointer);~SmartPointer();T *operator->();T &operator*();bool operator==(const SmartPointer<T> &other);bool operator!=(const SmartPointer<T> &other);private:T *m_pointer;};#endif
#ifndef _SMART_POINTER_HPP_#define _SMART_POINTER_HPP_#include "SmartPointer.h"template <typename T>SmartPointer<T>::SmartPointer(){m_pointer = 0;}template <typename T>SmartPointer<T>::SmartPointer(const T *pointer){m_pointer = const_cast<T*>(pointer);//std::cout<< "SmartPointer(const T *pointer)"<<std::endl;}template <typename T>SmartPointer<T>::~SmartPointer(){delete m_pointer;//std::cout<< "~SmartPointer"<<std::endl;}template <typename T>T *SmartPointer<T>::operator->(){return m_pointer;}template <typename T>T &SmartPointer<T>::operator*(){return *m_pointer;}template <typename T>bool SmartPointer<T>::operator==(const SmartPointer<T> &other){bool ret;if (m_pointer == other.m_pointer){ret = true;}else {ret = false;}return ret;}template <typename T>bool SmartPointer<T>::operator!=(const SmartPointer<T> &other){return !SmartPointer<T>::operator==(other);}#endif

#include "SmartPointer.hpp"#include <iostream>using namespace std;class Test{public:Test(){}~Test(){}void print(){cout<< "test class"<<endl;}};int main(){/*SmartPointer<int> p= new int(5);SmartPointer<int> p1;p1 = p;cout<< "*p1: "<<*p1<<endl;*p = 3;cout<< "*p: "<<*p<<endl;if (p != p1){cout<< "true"<<endl;}*/SmartPointer<Test> p2 = new Test[3];p2->print();p2.operator->()->print();return 0;}







0 0
原创粉丝点击