Advertisement
Guest User

Untitled

a guest
Feb 18th, 2012
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. namespace util
  2. {
  3.  
  4. class indexException:public std::exception
  5. {
  6. public:
  7. virtual const char* what()
  8. {
  9. return "Index is either too long, or negative";
  10. }
  11. };
  12.  
  13. class string
  14. {
  15. public:
  16. static const unsigned int length_max=100;
  17. string(const char* field=NULL)
  18. {
  19. if(field!=NULL)
  20. {
  21. const unsigned int length=strlen(field);
  22. this->field=new char[length+1];
  23. this->length=length;
  24. strcpy(this->field,field);
  25. }
  26. else
  27. {
  28. this->field=NULL;
  29. length=0;
  30. }
  31. }
  32. string(const string& str)
  33. {
  34. *this=str.field;
  35. }
  36. ~string()
  37. {
  38. if(length>0)
  39. delete[] field;
  40. length=0;
  41. }
  42. char& operator[] (int i) const throw()
  43. {
  44. try
  45. {
  46. if(i<0 || i>=(int)length)
  47. throw indexException();
  48. }
  49. catch(indexException& e)
  50. {
  51. std::cerr << e.what() << std::endl;
  52. }
  53. return field[i];
  54. }
  55. string& operator=(const char* field)
  56. {
  57. unsigned int length=0;
  58. if(field!=NULL)
  59. length=strlen(field);
  60. else
  61. field="";
  62. if(this->length>0)
  63. delete[] this->field;
  64. this->field=new char[length+1];
  65. this->length=length;
  66. strcpy(this->field,field);
  67. return *this;
  68. }
  69. string& operator= (const string& str)
  70. {
  71. if(this!=&str)
  72. *this=str.field;
  73. return *this;
  74. }
  75. operator char* ()
  76. {
  77. return field;
  78. }
  79. friend std::ostream& operator<< (std::ostream& out, string& str);
  80. friend std::istream& operator>> (std::istream& in, string& str);
  81. public:
  82. unsigned int length;
  83. char* field;
  84. };
  85.  
  86. std::ostream& operator<<(std::ostream& out, string& str)
  87. {
  88. out << str.field;
  89. return out;
  90. }
  91.  
  92. std::istream& operator>> (std::istream& in, string& str)
  93. {
  94. char temp[string::length_max];
  95. in >> temp;
  96. str=temp;
  97. return in;
  98. }
  99.  
  100. }
  101.  
  102. using namespace util;
  103.  
  104. int main(int argc, char **argv)
  105. {
  106. string str("ciao");
  107. string str2;
  108. str2=str;
  109. return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement