Comparaison (sur des structures/classes)

Sources d'information

Librairie(s) requise(s)

iostream

Comment ça marche

Fonction de comparaison de la structure (adresse) et des valeurs contenues dans l'objet

Dans le fichier .hpp, modification de la classe.

int     compare(Sample *other) const;

Ajouter ensuite les méthodes dans le fichier .cpp

int	Sample::compare(Sample *other) const
{
    if (this->_foo < other->getFoo())
        return (-1);
    else if (this->_foo > other->getFoo())
        return (1);
    return (0);
}

Dans le main.cpp

#include 
#include "Sample.class.hpp"

int	main(void)
{
    // physically different but structurally identical instances
    Sample instance1(42);
    Sample instance2(42);

    if (&instance1 == &instance1)
        std::cout << "instance 1 and instance 1 are physically equal" << std::endl;
    else
        std::cout << "instance 1 and instance 1 are not physically equal" << std::endl;

    if (&instance1 == &instance2)
        std::cout << "instance 1 and instance 2 are physically equal" << std::endl;
    else
        std::cout << "instance 1 and instance 2 are not physically equal" << std::endl;

    if (instance1.compare(&instance1) == 0)
        std::cout << "instance 1 and instance 1 are structurally equal" << std::endl;
    else
        std::cout << "instance 1 and instance 1 are not structurally equal" << std::endl;

    if (instance1.compare(&instance2) == 0)
        std::cout << "instance 1 and instance 2 are structurally equal" << std::endl;
    else
        std::cout << "instance 1 and instance 2 are not structurally equal" << std::endl;

    return (0);
}

retour


© 2022, vroch
Revisé le : 29 oct 2022
URL : http://vroch.ch/vr_tech_034.html
Main : http://vroch.ch