Advertisement
peterzig

[PO] Przeciążanie operatorów cz. II - dodawanie stringów

Apr 25th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. // ConsoleApplication3.cpp : Defines the entry point for the console application.
  2. //
  3. #define use_CRT_SECURE_NO_WARNINGS // to samo w Debug --> [nazwa pliku] Properties --> C/C++ --> Preprocessor Definitions : _CRT_SECURE_NO_WARNINGS
  4. #include "stdafx.h"
  5. #include <conio.h>
  6. #include <iostream>
  7. #include <malloc.h>
  8. #include <cstring>
  9.  
  10. class String
  11. {
  12. public:
  13.     String(char*);
  14.     String(const String &);
  15.  
  16.     String& operator = (const String &);
  17.     String& operator + (const String &);
  18.  
  19.     char* Txt() const;
  20.  
  21.     char & operator [] (int t);
  22.  
  23. private:
  24.     char* napis;
  25. };
  26.  
  27.  
  28. String::String(char* str)
  29. {
  30.     this->napis = (char*)malloc(sizeof(char) * strlen(str) + 1);
  31.     strcpy(this->napis, str);
  32. }
  33.  
  34. String::String(const String &str)
  35. {
  36.     this->napis = (char*)malloc(sizeof(char) * strlen(str.napis) + 1);
  37.     strcpy(this->napis, str.napis);
  38. }
  39.  
  40. String& String::operator = (const String &str)
  41. {
  42.     this->napis = (char*)malloc(sizeof(char) * strlen(str.napis) + 1);
  43.     strcpy(this->napis, str.napis);
  44.     return *this;
  45. }
  46.  
  47. String& String::operator + (const String &str)
  48. {
  49.     this->napis = (char*)realloc(this->napis, sizeof(char) * (strlen(this->napis) + strlen(str.napis)) + 1);
  50.     strcat(this->napis, str.napis);
  51.  
  52.     return *this;
  53. }
  54.  
  55. char & String::operator[](int t)
  56. {
  57.     return this->napis[t];
  58. }
  59.  
  60. char* String::Txt() const
  61. {
  62.     return this->napis;
  63. }
  64.  
  65. std::ostream& operator << (std::ostream &s, const String &str)
  66. {
  67.     return s << str.Txt();
  68. }
  69.  
  70. int main()
  71. {
  72.     String str("Napis 1");
  73.     String str2(" Napis 2");
  74.  
  75.     printf("%s\n", str.Txt());
  76.  
  77.     str = str2;
  78.  
  79.     printf("%s\n", str.Txt());
  80.  
  81.     String str3(" Napis 3");
  82.  
  83.     str = str2 + str3;
  84.  
  85.     printf("%s\n", str.Txt());
  86.  
  87.     std::cout << str << std::endl; //przeciazanie << coutem
  88.  
  89.     printf("%c\n", str[3]); //wypisuje trzeci indeks (czwarty znak) z tablicy str
  90.  
  91.     _getch();
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement