Guest User

Untitled

a guest
Feb 17th, 2019
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. template <class T>
  2. class Data
  3. {
  4. public:
  5. Data() {}
  6. ~Data() {}
  7.  
  8. public:
  9. T m_value;
  10. };
  11.  
  12. template <class T>
  13. class Data<T*>
  14. {
  15. public:
  16. Data() { m_value = new T();}
  17. //~Data() {delete m_value;} ********This gives error***
  18. ~Data() {} //****** This works
  19.  
  20. Data(const T* value) { m_value = new T(*value); }
  21. Data(const T value) { m_value = new T(value); }
  22.  
  23. template <class T>
  24. friend Data<T*> operator+(Data<T*> a, Data<T*> b);
  25.  
  26. Data<T*>& operator=(const Data<T*> value);
  27.  
  28. public:
  29. T* m_value;
  30. };
  31.  
  32.  
  33. //friend operator+
  34. template <class T>
  35. Data<T*> operator+(Data<T*> a, Data<T*> b)
  36. {
  37. Data<T*> temp(*a.m_value + *b.m_value);
  38. return temp;
  39. }
  40.  
  41. //member operator=
  42. template <class T>
  43. Data<T*>& Data<T*>::operator=(const Data<T*> value)
  44. {
  45. if (!this->m_value)
  46. this->m_value = new T();
  47.  
  48. *this->m_value = *value.m_value;
  49. return *this;
  50. }
  51.  
  52. ~Data() {delete m_value;} ********This gives error
  53.  
  54. ~Data() {} ********This works
  55.  
  56. void main()
  57. {
  58. typedef Data<int *> Data_Int;
  59.  
  60. Data_Int dt1(100);
  61. Data_Int dt2(200);
  62. Data_Int dt3;
  63.  
  64. dt3 = dt1 + dt2; // error line
  65.  
  66. cout << *dt3.m_value;
  67.  
  68. cin.ignore();
  69. }
  70.  
  71. if(this->m_value)
  72. delete m_value;
  73.  
  74. try
  75. {
  76. delete m_value;
  77. }
  78.  
  79. catch(std::exception& e)
  80. {
  81. cout << e.what();
  82. }
Add Comment
Please, Sign In to add comment