fork(1) download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstring>
  4. using namespace std;
  5.  
  6. class my_string {
  7. size_t length = 0;
  8. char *data = nullptr;
  9.  
  10. void set_data(char const *str) {
  11. length = strlen(str);
  12. if(data) {
  13. delete data;
  14. }
  15. data = strcpy(new char[length+1], str);
  16. }
  17. public:
  18. my_string(char const *str) {
  19. set_data(str);
  20. }
  21.  
  22. my_string(my_string const &other):
  23. my_string(other.c_str()) {}
  24.  
  25. char const * c_str() const {
  26. return data;
  27. }
  28.  
  29. string &operator=(char const *str) {
  30. set_data(str);
  31. return *this;
  32. }
  33.  
  34. string &operator=(my_string const &other) {
  35. set_data(other.c_str());
  36. return *this;
  37. }
  38.  
  39. ~my_string() {
  40. delete data;
  41. }
  42.  
  43. friend ostream &operator<<(ostream &out, my_string const &str) {
  44. return out << str.c_str();
  45. }
  46.  
  47. friend istream &operator>>(istream &in, my_string &str) {
  48. return in; //jestem w trakcie oglądania dr. house, jeśli chcesz sie bawic w relokacje to powodzonka
  49. }
  50. };
  51.  
  52. struct person {
  53. my_string name, surname;
  54. friend ostream &operator<<(ostream &out, person const &p) {
  55. return out << p.name << " " << p.surname;
  56. }
  57. };
  58.  
  59. int main() {
  60. person p = {
  61. "Adam", "Kowalski"
  62. };
  63. cout << p << endl;
  64. p.surname = "Malinowski";
  65. cout << p << endl;
  66. p.name = my_string("Janeczek");
  67. cout << p << endl;
  68. return 0;
  69. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In member function 'std::string& my_string::operator=(const char*)':
prog.cpp:31:11: error: invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'my_string'
   return *this;
           ^
prog.cpp: In member function 'std::string& my_string::operator=(const my_string&)':
prog.cpp:36:11: error: invalid initialization of reference of type 'std::string& {aka std::basic_string<char>&}' from expression of type 'my_string'
   return *this;
           ^
stdout

Standard output is empty