How to access members of a class with a class vector

0

I have the CClass class

//clase.h
class CClass{

public:

int suma (int X, int Y);

private:

int X;
int Y;
}

//clase.cpp

//constructor aqui

int
CClass::suma(intX, int Y){

int resultado = 0;

resultado = X + Y;

return resultado;
}

And in main.cpp I have created a block of memory with several objects of the class CClass with the help of a for and a pointer

//main.cpp

ifstream  fitxer(fichero);

if (fitxer.is_open())
{

   int = 0;

   delete[] m_Clase; //m_Clase es un apuntador al objeto de la clase declarado en main.h

   m_Clase = new CClass [10]; //reservo un bloque de memoria para 10 objetos CClass

   for (i=0; i<10; i++){

      is >> m_Clase[i];
   }

   fitxer.close();
}

Now I want to include a function in main.cpp to add the result of all the 'sum' functions of the different CClass objects

int suma total(/*???*/){

int total = 0;

//total = suma() + suma() + suma ()... etc
}

But I have no idea what variables I have to pass or how to complete it.

    
asked by Badwolf 04.04.2017 в 20:38
source

1 answer

0
  

But I have no idea what variables I have to pass him.

With the code provided, you have two options:

Pointer and size.

This approach is traditional in C, and equally valid in C ++ although less used.

int suma_total(const CClass *const arreglo, int tamanyo){

    int total = 0;

    for (int indice = 0; indice < tamanyo; ++indice)
        total += arreglo[índice].suma(?, ?);

    return total;
}

The call in main would look like:

m_Clase = new CClass [10];

// ...

int suma = suma_total(m_Clase, 10);

Start and end pointer.

This approach is traditional in C ++, and equally valid in C but less used.

int suma_total(const CClass *const inicio, const CClass *const fin){

    int total = 0;

    for (const CClass *clase = inicio; clase != fin; ++clase)
        total += clase->suma(?, ?);

    return total;
}

The call in main would look like:

m_Clase = new CClass [10];

// ...

int suma = suma_total(m_Clase, m_Clase + 10);

Problems.

  • The suma total function is misnamed, C ++ does not allow identifiers that contain spaces.
  • Parameter intX of CClass::suma is incorrect, I assume you wanted int X .
  • Parameters X e Y of function CClass::suma mask members X e Y of class CClass , use other names for parameters or for members.
  • Do not know what parameters you use X e Y of the function suma total , do you want to add the values of each instance of CClass or add values that will be provided from outside the class?
  • You may have more questions after reading this answer, do not hesitate to ask new questions.

        
    answered by 05.04.2017 в 09:15