How do I use a value from one class in another? in c ++

0

I have this code, everything is separated by header (.h) and implementation (.cpp) files:

Fitness.h

class Fitness
{

  private:

    // Professor's ID
    float _fit;

   public:

    // Inicia los datos del profesor
    Fitness(float fit);

    // Devuelve professor's ID
    inline float GetFit() const { return _fit; }
};

Fitness.cpp

#include "stdafx.h"
#include "Fitness.h"

// Inicializa los datos del fit este es el archivo cpp 
Fitness::Fitness(float fit) : _fit(fit) { } 

and the part where I use it is here in a class called Configuracion :

Configuration.h

class Configuracion
{

  public:

    //Lectura del Fitness
    hash_map<float, Fitness*> _fit;

  private:

    // Indica que aun no se lee la información
    bool _isEmpty;

  public:

    // Inicia datos
    Configuracion() : _isEmpty(true) { }

    // Libera recursos usados
    ~Configuracion();

    // Analiza datos y guarda datos
    void ParseFile(char* fileName);

    inline Fitness* GetFit(float fit)
    {
      hash_map<float, Fitness*>::iterator it = _fit.find(fit);
      return it != _fit.end() ? (*it).second : NULL;
    }

    inline float GetNFit() const { return (float)_fit.size(); }
    Fitness* ParseFitness(ifstream& file);

    // Remueve caracteres vacios al principio y fin de la cadena
    string& TrimString(string& str);
};

Configuration.cpp

Configuracion::~Configuracion()
{
  ////////////////////////////////////////////////
  for (hash_map<float, Fitness*>::iterator it = _fit.begin(); it != _fit.end(); it++)
    delete (*it).second;
}

void Configuracion::ParseFile(char* fileName)
{
  // Limpia objetos previamente analizados
  _fit.clear();
  string line;
  while( input.is_open() && !input.eof() )
  {
    // Leer linea por linea hasta que se obtenga el inicio de un nuevo objeto
    getline( input, line );
    TrimString( line );

    // Lee, analiza y guarda el tipo de objeto 
    if (line.compare("#fit") == 0)
    {
      Fitness* f = ParseFitness(input);

      if (f)
        _fit.insert(pair<float, Fitness*>(f->GetFit(), f));

    }
  }
  input.close();
  _isEmpty = false;

Then I want to use the value of the variable in another file called Horario.cpp

float f1 = 0.000000;
//f1 = Configuracion::GetInstance().GetFit();

f1 =(&Configuracion::_fit);

//Horario * f1= &Configuracion::_fit;
if (best->GetFitness() >= 0.45000000)//((&Configuracion::_fit)))//0.4500000 /*_fit/* (&Configuracion::_fit)*/)
{

on the line

f1 =(&Configuracion::_fit); 

I have the following error:

  

Error 2 error C2440: '=': can not convert from 'stdext :: hash_map, stdext :: hash_compare < _Kty, std :: less < _Kty > >, std :: allocator > Configuration :: 'to' float '

How can I avoid it so that working with the value works?

    
asked by JA Guerrero 20.11.2016 в 08:58
source

1 answer

2

If we analyze the call where the error occurs:

float f1 = 0.000000;
f1 =(&Configuracion::_fit);

We see the following:

  • f1 is of type float .
  • You try to assign to that float a pointer (for the & ). This is the first error, but there is more.
  • You are accessing Configuracion via static and yet _fit is not marked as static . 2nd error. Non-static members of a class are only accessible through an instance of the class. You imagine that I did something such that: std::cout << Alumno::Nombre . What student would you be referring to? you would not know how to say it, neither I nor the compiler, obviously, either ... hence this is treated as a mistake.
  • Member _fit is type hash_map<float, Fitness*> . Unless you implement an implicit implementation between both types the compiler will not know how to convert that hash_map into a float . 3rd mistake.

Possible solutions?

Class Horario should have access to an instance of type Configuracion . As you do not indicate the head of this class, let's imagine that it has something such that:

class Horario
{
  Configuracion m_config;
};

In this case, to access the configuration you could do something such that:

float f1 = 0.0000;
Fitness* fitness = m_config[f1];

Remember that in hash_map , the key is a float , then f1 you can only use it as an index to access a pointer of type Fitness .

Important : I personally would not use float or double as the key of any map. The reason is that these types of numbers are susceptible to receiving rounding. Floating-point numbers should never be compared with the comparison operator ( if( float1 == float2 ) ), and that is exactly what one or another map ends up doing to find the key ( it does not matter if you verify the real value or a hash). By doing this you can find that by passing a key that theoretically exists, the map does not return the expected object.

Solution 2

If it turns out that the Configuracion object must be unique and accessible for different objects, you can convert it to a Singleton:

class Configuracion
{
  private:
    Configuracion() // No se pueden crear objetos fuera de esta clase
    { }

    Configuracion(const Configuracion&) // Ni tampoco usar el constructor copia
    { }

  public:

    static Configuracion& Instance()
    {
      static Configuracion m_instance;
      return m_instance;
    }
};

And it would be used like this:

Configuracion::Instance()._fit[5.0] = new Fitness;

Additional note :

It is not usually advisable to have elements whose name starts with _ . The reason is that the constants and functions of the compiler usually start with that character and this can lead to strange errors when compiling. If you notice, you will see that I added the prefix m_ (m of member ) to the internal variables instead of _ to dry.

    
answered by 20.11.2016 / 22:54
source