How do Overload the assignment operator into a class that contains vector?

Asked

Viewed 67 times

0

I would like to do the allocation operator’s Overload (operator=), I know I have to reserve memory, and copy data from one to the other, however I do not know how to copy one vector to the other without knowing the size of the same.

    class Perfil{
    private:
       char letra; 
       vector <Carateristica*> carateristicas;
    }

    Perfil & Perfil::operator=(const Perfil & p1)
    {
        letra = p1.getLetra();

         // Agora deveria reservar memoria utilizando o new
             // e copiar os dados de um vector para o outro
    (..) 
}
  • The operator '=' returns a copy of the vector ...

1 answer

2


You can use the command forto traverse an array, and you can use the method push_back to add elements to a vector.

In the example below, the functions copy_from and release_old need to be implemented and depend on the type Caracteristica, that was not shown.

Actually it is not possible to give a precise answer because also the Profile class is not complete, for example missing the constructor and destructor.

class Perfil
{
   private:
      char letra; 
      vector<Carateristica*> carateristicas;
      char getLetra() { return letra; }

   public:
      Perfil& operator=(const Perfil&);
}

Perfil& Perfil::operator= (const Perfil& p1)
{
    for (auto c: caracteristicas)
    {
       release_old(c); // TODO: implementar 'release_old'
    }
    caracteristicas.clear(); // remove conteudo atual do vetor

    letra = p1.getLetra();
    for (auto c: p1.caracteristicas)
    {
       Caracteristica* new_c(copy_from(c)); // TODO: implementar 'copy_from'
       caracteristicas.push_back(new_c);
    }
    return *this;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.