operator overload

Sources d'information

Librairie(s) requise(s)

iostream

Comment ça marche

Cete bonne pratique nécessite au minimum

le fichier .hpp :

#ifndef SAMPLE_CLASS_HPP
# define SAMPLE_CLASS_HPP

#include

class Sample {

public:

    Sample( void );                 //canonical
    Sample( int const nb);
    Sample( Sample const & src );   //canonical
    ~Sample( void );                //canonical

    int     getNb( void ) const;

    Sample &   operator=( Sample const & rhs );   //canonical

private:

    int     _nb;

};

std::ostream & operator<<(std::ostream & o, Sample const & i);

#endif

le fichier .cpp :

#include <iostream>
#include "Sample.class.hpp"

    Sample::Sample( void ) : _nb(0)
    {
        std::cout << "Default Constructor called" << std::endl;
        return;

    }

    Sample::Sample( int const nb ) : _nb(nb)
    {
        std::cout << "Parametric Constructor called" << std::endl;
        return;
    }

        Sample::Sample( Sample const & src )
    {
        std::cout << "Copy constructor called" << std::endl;
        *this=src;
        return;
    }


    Sample::~Sample( void ) 
    {
        std::cout << "Destructor called"<< std::endl;
        return;
    }

    int     Sample::getNb( void ) const 
    {
        return (this->_nb);
    }

    Sample &   Sample::operator=( Sample const & rhs )
    {   
        std::cout << "Assignation operator called"<< this->_nb;
        
        if (this != &rhs)
        this->_nb = rhs.getNb();

        // retourne l'addresse de this, soit la reference
        return(*this);
    }


    // surcharge de simple fonction
    // surcharge de ostream <<
    std::ostream & operator<<( std::ostream & o, Sample const & rhs)
    {
        o << "The value of foo is :"<< rhs.getNb();
        return (o);
    }

le fichier main :

#include "Sample.class.hpp"

int main ()
{

    Sample instance1;
    Sample instance2 (42);
    Sample instance3(instance1);

    std::cout << instance1 << std::endl;
    std::cout << instance2 << std::endl;
    std::cout << instance3 << std::endl;

    instance3 = instance2;
    std::cout << instance3 << std::endl;

    return (0);
}

le resultat :

Default Constructor called
Parametric Constructor called
Copy constructor called
Assignation operator called22014The value of foo is :0
The value of foo is :42
The value of foo is :0
Assignation operator called0The value of foo is :42
Destructor called
Destructor called
Destructor called

retour


© 2022, vroch
Revisé le : 13 nov 2022
URL : http://vroch.ch/vr_tech_042.html
Main : http://vroch.ch