mardi 26 juin 2018

Errors I'm Having a Hard time Finding In This Code

so I have a final in 2 days, and I'm trying to understand a piece of code that is supposed to have a number of errors, and I'm not succeeding in finding any.. There is no solution with which I could analyze and fully understand and I feel that understanding this test fully will help me succeed in the final.

Any consideration would be appreciated, thank you.

The code:

#include <string.h>
#include <iostream>
using namespace std;

class Str
{
        char* word;
        int len;
public:
        Str(const char* w);
        Str(const Str& other);
        ~Str() {delete []word;}

        Str& operator=(const Str& other);
        char operator[](int i) const {return word[i];}
};

Str::Str(const char* w)
{
        len = strlen(w) + 1;
        word = new char[len];
        strcpy(word, w);
}

Str::Str(const Str& other)
{
        (*this) = other;
}

Str& Str::operator=(const Str& other)
{
        delete []word;
        len = other.len;
        word = new char[len];
        strcpy(word, other.word);
        return (*this);
}

int main()
{
        Str s1("hello");
        Str s2("hey");
        s2 = s1;
        s2 = "hi";
        Str s3(s1);
        s3[0] = 'H';

        return 0;
}

Aucun commentaire:

Enregistrer un commentaire