How to overload the assignment operator in a class containing vector?

0

I would like to overload the assignment operator ( 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 it .

    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
    (..) 
}
    
asked by anonymous 26.12.2016 / 21:40

1 answer

2

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

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

Actually it is not possible to give a precise answer because the Profile class is also not complete, for example the constructor and the 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;
}
    
27.12.2016 / 16:43