A
A
Alexander2017-01-11 03:36:44
C++ / C#
Alexander, 2017-01-11 03:36:44

Why displays kryakozyabry?

Good morning. Tell me who knows what the problem is? Thank you.
eebe123f9d1b49b786d19a072e49fdfb.PNG

class String {

private:
  char* _string;
  short _length;

public:
  
  String() {
    /*_length = 1;
    _string = new char[_length];
    _string[_length - 1] = '\0';*/
  }
  

  String(const char *s) {
    /*_length = strlen(s) + 1;
    
    cout << _length<<endl;
    _string = new char[_length];
    _string[_length - 1] = '\0';
    
    for (int i(0); i < (_length - 1); i++) {
      _string[i] = s[i];
    }
    _string[_length - 1] = NULL;*/
      
    //cout << "133"<<endl;

    _length = strlen(s) + 1;

    _string = (char*)malloc(_length);
    strcpy_s(_string, _length,s);

    //cout << _string<<endl;
  }

  
  String(const String &s) {
    cout << "String"<<endl;
    /*_length = s._length;
    _string = new char[_length];

    for (int i(0); i < (_length - 1); i++) {
      _string[i] = s._string[i];
    }
    if (_string[_length - 1] != '\0') { _string[_length - 1] = '\0'; }*/
  }
  

  ~String()
  {
    free(_string);
  }

  String& operator = (const String &s) {
    
    //if (this == &s) {
    //	return *this;
    //}
    //cout << "asdf";
    _length = s._length;
    _string = s._string;

    return *this;
  }

  int length() {
    return _length;
  }

  bool empty() {		
    return _string[0] == '\0';
  }

  friend ostream& operator <<(ostream & os, const String& s) {
    cout<< s._string<<endl;
    os << s._string;
    return os;
  }
};

int main() {

  SetConsoleCP(1251);
  SetConsoleOutputCP(1251);

  

  // Class String
  String  s;

  s = "mama myla ramy!";

  cout << s;

  cout << s.length() << endl;


  system("pause");

  //s = "";

  cout << s.length() << endl;

  if (s.empty())
  {
    cout << "Empty" << endl;
  }

  

  _getch();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2017-01-11
@15432

In the = operator, you are copying a pointer that can be cleared in the future.
Need to allocate memory and copy data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question