Error trying to create an array for types of a own Class

1

Hello, Good morning, everyone.

I want to assign a new data type of an array, for example:

I want my Array to be of the Person type, but it throws me an error, I've tried it in different ways. I do not know if this can be done?

One of the forms used:

#include <cstdlib>
#include <iostream>

using namespace std;

class Gente
{
      private:

      public:

      string Nombre;

};



int main()
{

Gente[] array = new Gente[2];
array[0].Nombre="Juan";
array[1].Nombre="Pedro";


system("PAUSE");

}

Error:

    
asked by Javier 20.04.2016 в 18:07
source

2 answers

3

You do not have a method to access the name property of your People class, either to initialize it or to obtain it, You have to create your class in this way:

class Gente {
  string nombre;

public:
  string getNombre()
  { return nombre; }
  void setNombre(string s){
      nombre = s;
  }
};

inside main () initializa:

Gente gente[4];
gente[0].setNombre("Juan");
gente[1].setNombre("Pedro");
gente[2].setNombre("Himi");
gente[3].setNombre("Korina");

Initialized your array you can read the values

cout << "gente:" << gente[i].getNombre() << "\n";

This is a complete example:

#include <iostream>
using namespace std;

    class Gente {
      int x;
      string nombre;

    public:
      string getNombre()
      { return nombre; }
      void setNombre(string s){
          nombre = s;
      }
    };

    int main()
    {
        Gente gente[4];
        gente[0].setNombre("Juan");
        gente[1].setNombre("Pedro");
        gente[2].setNombre("Himi");
        gente[3].setNombre("Korina");

         for(int i=0; i < 4; i++){
           cout << "nombre: " << gente[i].getNombre() << "\n";
         }

        return 0;
    }
    
answered by 20.04.2016 в 18:28
2

The declaration of the array would be fine if you were in C #. In C ++ it is done slightly differently:

Gente* array = new Gente[2];

If, on the other hand, you wanted to declare the array in the stack, without using dynamic memory and saving the subsequent delete (which you have not included), you could do something such that:

Gente array[2];

On the other hand, in C ++ there are containers that simplify the management of arrays and dynamic memory. In the case of vectors of fixed and predefined size we can use std :: array

std::array<Gente,2> miArray;

The advantage of using containers is that we have at our disposal a series of standard mechanisms to work with the elements, such as going through the list of elements using iterators.

Greetings.

    
answered by 20.04.2016 в 18:14