SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
8Q SHWLW WRXU GX &
                                  'LGLHU 'RQVH]

                                   ,679  89+

                           GRQVH]#XQLYYDOHQFLHQQHVIU




Didier DONSEZ 1995-1998          Un petit tour du C++             1

                                http://krimo666.mylivepage.com/
RPELQDLVRQ GH IRQFWLRQQDOLWpV
ODQJDJH 
      - Performances
           SURJUDPPDWLRQ VVWqPH



ODQJDJH $'$
      Concept de Généricité et de Modularité

      Surcharge

ODQJDJH 22
      Héritage Statique (simple et multiple)

      Spécialisation - Généralisation - Abstraction
           6PDOOWDON 2EM/LVS (LIIHO 2EMHFWLYH -DYD« HW ELHQ V€U 


Didier DONSEZ 1995-1998              Un petit tour du C++                   2

                                     http://krimo666.mylivepage.com/
OD VQWD[H GH EDVH  OH ODQJDJH 

VQWD[WH FODVVLTXH
      type de base
               (char, int, long, float, double, unsigned ....)

      type constructeur
               (array [], struct, union)

      opérateurs, expressions, blocs, structures de contrôle
              (if, switch, while, for )

      fonctions
                  (bibliothéque d'entrée/sortie)




Didier DONSEZ 1995-1998                 Un petit tour du C++              3

                                        http://krimo666.mylivepage.com/
([WHQVLRQ GX ODQJDJH 
      référence 
           QRPPDJH PXOWLSOH G
XQ REMHW
   int a;
   int abis = a;

           VLPSOLILFDWLRQ G
pFULWXUH SRXU SDUDPrWUHV SDU YDULDEOH
   int   inc_ptr(int* i) { return ++(*i); }
   int   b,c;
   c =   inc_ptr(b);
   int   inc_ref(int i) { return ++i; }
   c =   inc_ref(b) ;

      surcharge de fonctions
   void print( int ) { ... };
   void print( double ) { ... };
   void print( char* ) { ... };

      fonction inline
   inline int increment(int a) { return ++a; }
   #define INCREMENT(A) (++(A))

Didier DONSEZ 1995-1998            Un petit tour du C++             4

                                  http://krimo666.mylivepage.com/
$SSRUW GH ODQJDJH 22 
                            OHV FODVVHV G
REMHWV
      encapsulation des membres, manipulation au travers des méthodes.
   class Entreprise {
       // membres
     int nbEmployes
     Employe* listePersonnel[MAX_Pers];
   public:
       // constructeur/destructeur
     Entreprise();
     Entreprise(Entreprise*);
     ˜Entreprise();
   private:
       // méthodes
     void embauche(Employe*, int sal=SAL_SMIC)
     void debauche(Employe*);
     void debauche(Employe*, int primeDepart); //surcharge
   public:
       // méthodes d'opérateur
     Entreprise operator += (Employe* e)
     inline Entreprise operator -= (Employe* e)
                        { debauche(e); return *this; }
   }

Didier DONSEZ 1995-1998           Un petit tour du C++                   5

                                  http://krimo666.mylivepage.com/
'pFODUDWLRQV ,PEULTXpHV
   class List {
     class Element { public: ...
       give(Obj o);
     };
   public:
     insert(Obj o);
   };
   class List {
     class Element { public: ...
       alloc(Obj o);
     };
   public:
     insert(Obj o);
   };
   Array::Element::give(Obj o) { ... }
   List::Element::alloc(Obj o) { ... }

   class Process { public:
      enum Status { IDLE, RUNNING };
       Status st;
       ...
   };
   schedule() {
       Process::Status st = IDLE;
       ...
   }

Didier DONSEZ 1995-1998            Un petit tour du C++              6

                                   http://krimo666.mylivepage.com/
$SSRUW GH ODQJDJH 22 
                          PDQLSXODWLRQ GHV REMHWV
   main() {
   Entreprise IBM; // constructeur 1
   Entreprise* Bell = new Entreprise; // ex-malloc + constructeur 1
   Employe durant;
   Employe* p_durant = durant
   Employe martin;

   IBM.embauche(p_durant);
   IBM -= p_durant;
   Bell-embauche(p_durant);
   (Bell) += martin;

   Entreprise ATT(Bell); // constructeur 2
                          // instanciation au milieu du code
   delete Bell; // desallocateur + destructeur
   ATT -= p_durant; //
   } // en sortie de bloc
     // destructeur ˜Entreprise() pour IBM, ATT
     // destructeur ˜Employe() pour durant, martin



Didier DONSEZ 1995-1998          Un petit tour du C++                 7

                                 http://krimo666.mylivepage.com/
RQVWUXFWHXUV 'HVWUXFWHXU
RQVWUXFWHXUV 0ODVV
MyClass() est généré par défaut mais il peut être surchargé

      Il est invoqué lors de la déclaration des variables locales (et paramêtres) et par
        l'opérateur MyClass::new()

      NB : MyClass(MyClass) peut être invoqué lors d'une affectation

'HVWUXFWHXU a0ODVV
généré par défaut mais il peut être surchargé une seule fois

      Il est invoqué sur les variables locales (et paramêtres) à la sortie d'un bloc (ou de la
        fonction) et par l'opérateur MyClass::delete()




Didier DONSEZ 1995-1998               Un petit tour du C++                            8

                                      http://krimo666.mylivepage.com/
$OORFDWHXU 'pVDOORFDWHXU
$OORFDWHXU RSHUDWRU 0ODVVQHZ
généré par défaut mais il peut être surchargé

$OORFDWHXU RSHUDWRU QHZ
l'opérateur ::new() est l'allocateur globale
      il existe par défaut mais il peut être surchargé

'pVDOORFDWHXU RSHUDWRU 0ODVVGHOHWH
généré par défaut mais il peut être surchargé

'pVDOORFDWHXU RSHUDWRU GHOHWH
l'opérateur ::delete() est l'allocateur globale

      il existe par défaut mais il peut être surchargé




Didier DONSEZ 1995-1998                Un petit tour du C++              9

                                       http://krimo666.mylivepage.com/
RQVWUXFWHXUV 'HVWUXFWHXU
      $OORFDWHXU 'pVDOORFDWHXU ([HPSOH
class Str { public:
     char* cs;
     Str()         { cs=(char*)NIL; };
     Str(char* cs) {
       this-cs=new char[strlen(cs)+1]; strcpy(this-cs,cs);};
     Str(const Str s){
       if(this-cs!=(char*)NIL) delete this-cs;
       this-cs=new char[strlen(s.cs)+1]; strcpy(this-cs,cs.s);};
     ~Str()        { if(this-cs!=(char*)NIL) delete this-cs; };
   };

   Str func(Str p){        // Str::Str(const Str) pour p
     Str v1;                // Str::Str() pour v1
     ...
     {
        Str v2(v1);         // Str::Str(const Str) pour v2
        Str v3 = v2;        // Str::Str(const Str) pour v3
       ...
     }                      // Str::~Str pour v3, v2
     ...
   }                        // Str::~Str pour v1, p
   int main(){    Str m1(toto);    // Str::Str(char*) pour m1
                  Str m2 = func(m1); // Str::Str(const Str) pour m2
   }

Didier DONSEZ 1995-1998           Un petit tour du C++                 10

                                  http://krimo666.mylivepage.com/
2SpUDWHXUV
      Définition des Opérateurs
          PpWKRGHV DSSHOpHV DYHF XQH IRUPH VQWD[LTXH DOJpEULTXH
   class Obj;
   class ListObj { public: ...
                 ListObj();
                 ListObj(const ListObj);
      ListObj   operator =(const ListObj);
      ListObj   operator +=(const ListObj);
      ListObj   operator +=(const Obj);
      const Obj operator [](long);
   };

   ListObj operator + (const ListObj, const ListObj );

      Utilisation des Opérateurs
   ListObj l2, l3;
   ListObj   l1(l3); //     ListObj(const ListObj);
                   // vs ListObj();l1.operator=(l3);
   l1 += l2;    // l1.operator+=( l2 )
   l1 += l3[0];    // l1.operator+=( l3.operator[](0) )
   l1 = l2 + l3; // l1.operator=( operator+(l2,l3) );

Didier DONSEZ 1995-1998            Un petit tour du C++              12

                                   http://krimo666.mylivepage.com/
+pULWDJHV 6LPSOH HW 0XOWLSOH
                      OHV RQVWUXFWHXUV
class Person { public:
        char* nom;
     Person(char* nom) {
        this-nom = new char[strlen(nom)+1];
        strcpy(this-nom, nom);
    };
   }
class Etudiant : public Person { public:
        char* etude;
     Etudiant (char* nom, char* etu) : Person(nom) {
        etude = new char[strlen(nom)+1];
        strcpy( etude, etu);
     };
   }
class Employe : public Person { public:
        int echelon;
     Employe(char* nom, int ech) : Person(nom), echelon(ech) {};
   }
class Etudiant_en_FormCont: public Etudiant, virtual public Employe {
    public:
     Etudiant_en_FormCont(char* nom, char* etu, int ech)
        : Etudiant(nom,etu), Employe(nom, ech) {};
   }


Didier DONSEZ 1995-1998          Un petit tour du C++                   13

                                 http://krimo666.mylivepage.com/
0pWKRGHV 9LUWXHOOHV
                          0pWKRGHV QRQ 9LUWXHOOHV
   class Person { public:
       char* nom;
       virtual    printVIRT() { cout  nom;};
                  print()     { cout  nom;};
   };
   class Employe : public Person { public:
       int echelon;
       virtual printVIRT() { Person::printVIRT(); cout  echelon; };
               print()      { Person::print();      cout  echelon; };
               print2()         { Employe::print(); };
   };

   f(){
           Employe Bill;
           Employe e =  Bill;
           Person p = e;     // Person p =  Bill;

           e-printVIRT();   // Employe::printVIRT()
           e-print();          // Employe::print()
           e-print2();         // Employe::print2()
           p-printVIRT();   // Employe::printVIRT() (abstraction)
           p-print();          // Person::print()
           p-print2();         // Erreur de Compilation
   }

Didier DONSEZ 1995-1998             Un petit tour du C++                  14

                                   http://krimo666.mylivepage.com/
+pULWDJH 0XOWLSOH HW 0pWKRGHV
  class Person { public:
       char* nom;
     virtual print() { cout  nom;};
  }
class Employe : public Person { public:
       int echelon;
     virtual print() {            // spécialisation
             Person::print();
             cout  echelon;
   };
  }
class Etudiant : public Person { public:
       char* etude;
     virtual print() {            // spécialisation
             Person::print();
             cout  etude;
   };
  }
class Etudiant_en_FormCont: public Etudiant, virtual public Employe {
    public:
     virtual print() {      Etudiant::print();
                         Employe::print();
   };

Didier DONSEZ 1995-1998      Un petit tour du C++                 15

                             http://krimo666.mylivepage.com/
ODVVHV $EVWUDLWHV SXUH YLUWXDO
pas d’instanciation possible pour ces classes
   class Figure {         public:
      virtual void        draw()=0;
   };
   class Circle :         public Figure {
      virtual void        draw() { ... };
   };

   Figure fig;             // KO
   Circle circle;          // OK


           5HPDUTXH GpILQLWLRQ RSWLRQHOOH GH Figure::draw()




Didier DONSEZ 1995-1998               Un petit tour du C++              16

                                      http://krimo666.mylivepage.com/
RQWU{OH G
$FFHV ,  'pILQLWLRQ
Private (défaut)
           VHXOHPHQW
            PpWKRGHV PHPEUHV
            LQLWLDOLVHXUV GH OD FODVVH
            PpWKRGHV IULHQG

      Protected
           HQ SOXV
            PpWKRGHV PHPEUHV G
XQH FODVVH GpULYpH

      Public
             WRXWHV PpWKRGHV RX IRQFWLRQV




Didier DONSEZ 1995-1998             Un petit tour du C++              17

                                    http://krimo666.mylivepage.com/
RQWU{OH G
$FFHV ,,  8WLOLVDWLRQ
class Base {                              class Derive : public Base {
       private:                                    int   d();
         int    a;                               protected:
       protected:                                  int   e;
         int    b();                             public:
       public:                                     int   f;
         int    c;                            };
       private:
         int    g();
    };

Base::g() {               Derive::g() {                      f(Base bs, Derive
  a++; // OK                a++; // OK                       dr){
  b(); // OK                b(); // OK                         bs.a++; // Error
  c++; // OK                c++; // OK                         bs.b(); // Error
}                                                              bs.c++; // OK
                              d();   // OK
                              e++;   // OK                        dr.d();   // Error
                              f++;   // OK                        dr.e++;   // Error
                          }                                       dr.f++;   // OK
                                                             }




Didier DONSEZ 1995-1998          Un petit tour du C++                              18

                                http://krimo666.mylivepage.com/
RQWU{OH G
$FFHV ,,,  +HULWDJH
class Base {                      class Derive                      class DD : Derive {
  private:   int          a;         : XXXXX Base {                   fDD(Derive);
  protected: int          b();                 int   d();           };
  public:    int          c;        protected int    e;
  private:   int          g();      public:    int   f;
};                                };
XXXXX = public                      XXXXX = protected                    XXXXX = private

DD::fDD(Derive dr){              DD::fDD(Derive dr){              DD::fDD(Derive dr){
  dr.a++; // Error                  dr.a++; // Error                  dr.a++; // Error
  dr.b(); // OK                     dr.b(); // OK                     dr.b(); // Error
  dr.c++; // OK                     dr.c++; // OK                     dr.c++; // Error
}                                 }                                 }
f(Derive dr){                    f(Derive dr){                    f(Derive dr){
  dr.a++; // Error                  dr.a++; // Error                  dr.a++; // Error
  dr.b(); // Error                  dr.b(); // Error                  dr.b(); // Error
  dr.c++; // OK                     dr.c++; // Error                  dr.c++; // Error
}                                 }                                 }

   la classe Derive rend public    la classe Derive rend public               la classe Derive
        le contrôle d'accès             le contrôle d'accès                 ne rend pas public
        de sa super-classe              de sa super-classe                  le contrôle d'accès
              à tous                        uniquement                      de sa super-classe
                                    à ses sous classes et aux
                                              friends
Didier DONSEZ 1995-1998                 Un petit tour du C++                                      19

                                       http://krimo666.mylivepage.com/

Más contenido relacionado

La actualidad más candente

Null Coalescing Operator
Null Coalescing OperatorNull Coalescing Operator
Null Coalescing OperatorDarkmira
 
Sécurité et Quaité de code PHP
Sécurité et Quaité de code PHPSécurité et Quaité de code PHP
Sécurité et Quaité de code PHPJean-Marie Renouard
 
Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !Engineor
 
C++11 en 12 exemples simples
C++11 en 12 exemples simplesC++11 en 12 exemples simples
C++11 en 12 exemples simplesPethrvs
 
Lect14 dev2
Lect14 dev2Lect14 dev2
Lect14 dev2moisko
 
TP3: Comportement Temps Réel de l'Agent Perception
TP3: Comportement Temps Réel de l'Agent PerceptionTP3: Comportement Temps Réel de l'Agent Perception
TP3: Comportement Temps Réel de l'Agent PerceptionSaid Benaissa
 
Les patrons de conception du composant Form
Les patrons de conception du composant FormLes patrons de conception du composant Form
Les patrons de conception du composant FormVladyslav Riabchenko
 
La programmation fonctionnelle avec le langage OCaml
La programmation fonctionnelle avec le langage OCamlLa programmation fonctionnelle avec le langage OCaml
La programmation fonctionnelle avec le langage OCamlStéphane Legrand
 
Top 10 chausse trappes
Top 10 chausse trappesTop 10 chausse trappes
Top 10 chausse trappesDamien Seguy
 

La actualidad más candente (20)

Client base de données en PHP5
Client base de données en PHP5Client base de données en PHP5
Client base de données en PHP5
 
Null Coalescing Operator
Null Coalescing OperatorNull Coalescing Operator
Null Coalescing Operator
 
Sécurité et Quaité de code PHP
Sécurité et Quaité de code PHPSécurité et Quaité de code PHP
Sécurité et Quaité de code PHP
 
Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !Open close principle, on a dit étendre, pas extends !
Open close principle, on a dit étendre, pas extends !
 
PHP5 et les fichiers
PHP5 et les fichiersPHP5 et les fichiers
PHP5 et les fichiers
 
Le client HTTP PHP5
Le client HTTP PHP5Le client HTTP PHP5
Le client HTTP PHP5
 
Syntaxe du langage PHP
Syntaxe du langage PHPSyntaxe du langage PHP
Syntaxe du langage PHP
 
C++11 en 12 exemples simples
C++11 en 12 exemples simplesC++11 en 12 exemples simples
C++11 en 12 exemples simples
 
Etes vous-pret pour php8 ?
Etes vous-pret pour php8 ?Etes vous-pret pour php8 ?
Etes vous-pret pour php8 ?
 
Cours php
Cours phpCours php
Cours php
 
Ruby STAR
Ruby STARRuby STAR
Ruby STAR
 
Lect14 dev2
Lect14 dev2Lect14 dev2
Lect14 dev2
 
Examen 2011 exo 4
Examen 2011 exo 4Examen 2011 exo 4
Examen 2011 exo 4
 
TP3: Comportement Temps Réel de l'Agent Perception
TP3: Comportement Temps Réel de l'Agent PerceptionTP3: Comportement Temps Réel de l'Agent Perception
TP3: Comportement Temps Réel de l'Agent Perception
 
Tp appel procedure
Tp appel procedureTp appel procedure
Tp appel procedure
 
Fichier XML et PHP5
Fichier XML et PHP5Fichier XML et PHP5
Fichier XML et PHP5
 
Les patrons de conception du composant Form
Les patrons de conception du composant FormLes patrons de conception du composant Form
Les patrons de conception du composant Form
 
La programmation fonctionnelle avec le langage OCaml
La programmation fonctionnelle avec le langage OCamlLa programmation fonctionnelle avec le langage OCaml
La programmation fonctionnelle avec le langage OCaml
 
Cours php
Cours phpCours php
Cours php
 
Top 10 chausse trappes
Top 10 chausse trappesTop 10 chausse trappes
Top 10 chausse trappes
 

Destacado

Conférence Accessibilité Intuiti - Support
Conférence Accessibilité Intuiti - SupportConférence Accessibilité Intuiti - Support
Conférence Accessibilité Intuiti - SupportArnaud BRIAND
 
Présentation Energy Enhancer
Présentation Energy EnhancerPrésentation Energy Enhancer
Présentation Energy EnhancerHerve Royal
 
Etude SNCD - Marketing Mobile Attitude - MMA 2013
Etude SNCD - Marketing Mobile Attitude - MMA 2013Etude SNCD - Marketing Mobile Attitude - MMA 2013
Etude SNCD - Marketing Mobile Attitude - MMA 2013Anthony Deydier
 
Practica docente y seleccion de tic. necesidad de criterios
Practica docente y seleccion de tic. necesidad de criteriosPractica docente y seleccion de tic. necesidad de criterios
Practica docente y seleccion de tic. necesidad de criteriosEduardo R. Diaz Madero
 
E gane presentación intermediarios de seguros
E gane presentación intermediarios de segurosE gane presentación intermediarios de seguros
E gane presentación intermediarios de segurosJose Leonardo Galvez
 
Le commerce bilatéral france algérie au 1er semestre 2015
Le commerce bilatéral france algérie au 1er semestre 2015Le commerce bilatéral france algérie au 1er semestre 2015
Le commerce bilatéral france algérie au 1er semestre 2015OUADA Yazid
 
100paraules pal
100paraules pal100paraules pal
100paraules palMaribelSD
 
Sip innovcit-nouveaux profs
Sip innovcit-nouveaux profsSip innovcit-nouveaux profs
Sip innovcit-nouveaux profsinnovacite
 

Destacado (20)

Emairel
EmairelEmairel
Emairel
 
Cetoacidosis
CetoacidosisCetoacidosis
Cetoacidosis
 
Presentacion Prosercol Asesores Ltda
Presentacion Prosercol Asesores LtdaPresentacion Prosercol Asesores Ltda
Presentacion Prosercol Asesores Ltda
 
Conférence Accessibilité Intuiti - Support
Conférence Accessibilité Intuiti - SupportConférence Accessibilité Intuiti - Support
Conférence Accessibilité Intuiti - Support
 
Argumentacióny litigaciónoral
Argumentacióny litigaciónoralArgumentacióny litigaciónoral
Argumentacióny litigaciónoral
 
Présentation Energy Enhancer
Présentation Energy EnhancerPrésentation Energy Enhancer
Présentation Energy Enhancer
 
Etude SNCD - Marketing Mobile Attitude - MMA 2013
Etude SNCD - Marketing Mobile Attitude - MMA 2013Etude SNCD - Marketing Mobile Attitude - MMA 2013
Etude SNCD - Marketing Mobile Attitude - MMA 2013
 
Practica docente y seleccion de tic. necesidad de criterios
Practica docente y seleccion de tic. necesidad de criteriosPractica docente y seleccion de tic. necesidad de criterios
Practica docente y seleccion de tic. necesidad de criterios
 
Qué es un blog
Qué es un blogQué es un blog
Qué es un blog
 
Celiaquía (lengua)
Celiaquía  (lengua)Celiaquía  (lengua)
Celiaquía (lengua)
 
Aboliyahshualatorah
AboliyahshualatorahAboliyahshualatorah
Aboliyahshualatorah
 
Rapport de curation web
Rapport de curation webRapport de curation web
Rapport de curation web
 
E gane presentación intermediarios de seguros
E gane presentación intermediarios de segurosE gane presentación intermediarios de seguros
E gane presentación intermediarios de seguros
 
Estadistica esad
Estadistica esadEstadistica esad
Estadistica esad
 
Presentación de la jornada
Presentación de la jornadaPresentación de la jornada
Presentación de la jornada
 
Murmure25 16mai
Murmure25 16maiMurmure25 16mai
Murmure25 16mai
 
Le commerce bilatéral france algérie au 1er semestre 2015
Le commerce bilatéral france algérie au 1er semestre 2015Le commerce bilatéral france algérie au 1er semestre 2015
Le commerce bilatéral france algérie au 1er semestre 2015
 
100paraules pal
100paraules pal100paraules pal
100paraules pal
 
Sip innovcit-nouveaux profs
Sip innovcit-nouveaux profsSip innovcit-nouveaux profs
Sip innovcit-nouveaux profs
 
Le Club des Partenaires
Le Club des PartenairesLe Club des Partenaires
Le Club des Partenaires
 

Similar a Tour C++

Corrigé langage c
Corrigé langage cCorrigé langage c
Corrigé langage ccoursuniv
 
Chap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdfChap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdframadanmahdi
 
Corrigés exercices langage C
Corrigés exercices langage CCorrigés exercices langage C
Corrigés exercices langage Ccoursuniv
 
Cours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMACours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMALoic Yon
 
VIM puissance PHP = VI Improved !
VIM puissance PHP = VI Improved !VIM puissance PHP = VI Improved !
VIM puissance PHP = VI Improved !Frederic Hardy
 
PL LSQL.pptx
PL LSQL.pptxPL LSQL.pptx
PL LSQL.pptxMaNl13
 
20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soatSOAT
 
C1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partieC1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partieLoic Yon
 
Partie 14: Entrée/Sortie — Programmation orientée objet en C++
Partie 14: Entrée/Sortie — Programmation orientée objet en C++Partie 14: Entrée/Sortie — Programmation orientée objet en C++
Partie 14: Entrée/Sortie — Programmation orientée objet en C++Fabio Hernandez
 
De java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvementsDe java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvementsDidier Plaindoux
 
Les nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ ModerneLes nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ ModerneMicrosoft
 
Gestion des logs sur une plateforme web
Gestion des logs sur une plateforme webGestion des logs sur une plateforme web
Gestion des logs sur une plateforme webfredcons
 
Partie1 TypeScript
Partie1 TypeScriptPartie1 TypeScript
Partie1 TypeScriptHabib Ayad
 

Similar a Tour C++ (20)

Corrigé langage c
Corrigé langage cCorrigé langage c
Corrigé langage c
 
Chap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdfChap 2--POO avec JAVA.pdf
Chap 2--POO avec JAVA.pdf
 
Corrigés exercices langage C
Corrigés exercices langage CCorrigés exercices langage C
Corrigés exercices langage C
 
Cours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMACours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMA
 
Algo poo ts
Algo poo tsAlgo poo ts
Algo poo ts
 
Support programmation orientée objet c# .net version f8
Support programmation orientée objet c#  .net version f8Support programmation orientée objet c#  .net version f8
Support programmation orientée objet c# .net version f8
 
VIM puissance PHP = VI Improved !
VIM puissance PHP = VI Improved !VIM puissance PHP = VI Improved !
VIM puissance PHP = VI Improved !
 
PL LSQL.pptx
PL LSQL.pptxPL LSQL.pptx
PL LSQL.pptx
 
20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat20140123 java8 lambdas_jose-paumard-soat
20140123 java8 lambdas_jose-paumard-soat
 
C1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partieC1 - Langage C - ISIMA - Première partie
C1 - Langage C - ISIMA - Première partie
 
Partie 14: Entrée/Sortie — Programmation orientée objet en C++
Partie 14: Entrée/Sortie — Programmation orientée objet en C++Partie 14: Entrée/Sortie — Programmation orientée objet en C++
Partie 14: Entrée/Sortie — Programmation orientée objet en C++
 
TAD (1).pptx
TAD (1).pptxTAD (1).pptx
TAD (1).pptx
 
De java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvementsDe java à swift en 2 temps trois mouvements
De java à swift en 2 temps trois mouvements
 
Les nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ ModerneLes nouveautés de C++11 : Ecrire du C++ Moderne
Les nouveautés de C++11 : Ecrire du C++ Moderne
 
Cours javascript v1
Cours javascript v1Cours javascript v1
Cours javascript v1
 
Ch07
Ch07Ch07
Ch07
 
Cascalog présenté par Bertrand Dechoux
Cascalog présenté par Bertrand DechouxCascalog présenté par Bertrand Dechoux
Cascalog présenté par Bertrand Dechoux
 
Gestion des logs sur une plateforme web
Gestion des logs sur une plateforme webGestion des logs sur une plateforme web
Gestion des logs sur une plateforme web
 
Partie1 TypeScript
Partie1 TypeScriptPartie1 TypeScript
Partie1 TypeScript
 
Php4 Mysql
Php4 MysqlPhp4 Mysql
Php4 Mysql
 

Último

Computer Parts in French - Les parties de l'ordinateur.pptx
Computer Parts in French - Les parties de l'ordinateur.pptxComputer Parts in French - Les parties de l'ordinateur.pptx
Computer Parts in French - Les parties de l'ordinateur.pptxRayane619450
 
Chapitre 2 du cours de JavaScript. Bon Cours
Chapitre 2 du cours de JavaScript. Bon CoursChapitre 2 du cours de JavaScript. Bon Cours
Chapitre 2 du cours de JavaScript. Bon Coursebenezerngoran
 
L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...
L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...
L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...Faga1939
 
Boléro. pptx Film français réalisé par une femme.
Boléro.  pptx   Film   français   réalisé  par une  femme.Boléro.  pptx   Film   français   réalisé  par une  femme.
Boléro. pptx Film français réalisé par une femme.Txaruka
 
Bilan énergétique des chambres froides.pdf
Bilan énergétique des chambres froides.pdfBilan énergétique des chambres froides.pdf
Bilan énergétique des chambres froides.pdfAmgdoulHatim
 
Conférence Sommet de la formation 2024 : Développer des compétences pour la m...
Conférence Sommet de la formation 2024 : Développer des compétences pour la m...Conférence Sommet de la formation 2024 : Développer des compétences pour la m...
Conférence Sommet de la formation 2024 : Développer des compétences pour la m...Technologia Formation
 
Copie de Engineering Software Marketing Plan by Slidesgo.pptx.pptx
Copie de Engineering Software Marketing Plan by Slidesgo.pptx.pptxCopie de Engineering Software Marketing Plan by Slidesgo.pptx.pptx
Copie de Engineering Software Marketing Plan by Slidesgo.pptx.pptxikospam0
 
Sidonie au Japon . pptx Un film français
Sidonie    au   Japon  .  pptx  Un film françaisSidonie    au   Japon  .  pptx  Un film français
Sidonie au Japon . pptx Un film françaisTxaruka
 
Formation qhse - GIASE saqit_105135.pptx
Formation qhse - GIASE saqit_105135.pptxFormation qhse - GIASE saqit_105135.pptx
Formation qhse - GIASE saqit_105135.pptxrajaakiass01
 
Cours ofppt du Trade-Marketing-Présentation.pdf
Cours ofppt du Trade-Marketing-Présentation.pdfCours ofppt du Trade-Marketing-Présentation.pdf
Cours ofppt du Trade-Marketing-Présentation.pdfachrafbrahimi1
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...Nguyen Thanh Tu Collection
 
La nouvelle femme . pptx Film français
La   nouvelle   femme  . pptx  Film françaisLa   nouvelle   femme  . pptx  Film français
La nouvelle femme . pptx Film françaisTxaruka
 
Apolonia, Apolonia.pptx Film documentaire
Apolonia, Apolonia.pptx         Film documentaireApolonia, Apolonia.pptx         Film documentaire
Apolonia, Apolonia.pptx Film documentaireTxaruka
 
COURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdf
COURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdfCOURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdf
COURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdfabatanebureau
 
L application de la physique classique dans le golf.pptx
L application de la physique classique dans le golf.pptxL application de la physique classique dans le golf.pptx
L application de la physique classique dans le golf.pptxhamzagame
 
Cours Préparation à l’ISO 27001 version 2022.pdf
Cours Préparation à l’ISO 27001 version 2022.pdfCours Préparation à l’ISO 27001 version 2022.pdf
Cours Préparation à l’ISO 27001 version 2022.pdfssuserc72852
 
Formation échiquéenne jwhyCHESS, parallèle avec la planification de projet
Formation échiquéenne jwhyCHESS, parallèle avec la planification de projetFormation échiquéenne jwhyCHESS, parallèle avec la planification de projet
Formation échiquéenne jwhyCHESS, parallèle avec la planification de projetJeanYvesMoine
 
Les roches magmatique géodynamique interne.pptx
Les roches magmatique géodynamique interne.pptxLes roches magmatique géodynamique interne.pptx
Les roches magmatique géodynamique interne.pptxShinyaHilalYamanaka
 

Último (18)

Computer Parts in French - Les parties de l'ordinateur.pptx
Computer Parts in French - Les parties de l'ordinateur.pptxComputer Parts in French - Les parties de l'ordinateur.pptx
Computer Parts in French - Les parties de l'ordinateur.pptx
 
Chapitre 2 du cours de JavaScript. Bon Cours
Chapitre 2 du cours de JavaScript. Bon CoursChapitre 2 du cours de JavaScript. Bon Cours
Chapitre 2 du cours de JavaScript. Bon Cours
 
L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...
L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...
L'ÉVOLUTION DE L'ÉDUCATION AU BRÉSIL À TRAVERS L'HISTOIRE ET LES EXIGENCES DE...
 
Boléro. pptx Film français réalisé par une femme.
Boléro.  pptx   Film   français   réalisé  par une  femme.Boléro.  pptx   Film   français   réalisé  par une  femme.
Boléro. pptx Film français réalisé par une femme.
 
Bilan énergétique des chambres froides.pdf
Bilan énergétique des chambres froides.pdfBilan énergétique des chambres froides.pdf
Bilan énergétique des chambres froides.pdf
 
Conférence Sommet de la formation 2024 : Développer des compétences pour la m...
Conférence Sommet de la formation 2024 : Développer des compétences pour la m...Conférence Sommet de la formation 2024 : Développer des compétences pour la m...
Conférence Sommet de la formation 2024 : Développer des compétences pour la m...
 
Copie de Engineering Software Marketing Plan by Slidesgo.pptx.pptx
Copie de Engineering Software Marketing Plan by Slidesgo.pptx.pptxCopie de Engineering Software Marketing Plan by Slidesgo.pptx.pptx
Copie de Engineering Software Marketing Plan by Slidesgo.pptx.pptx
 
Sidonie au Japon . pptx Un film français
Sidonie    au   Japon  .  pptx  Un film françaisSidonie    au   Japon  .  pptx  Un film français
Sidonie au Japon . pptx Un film français
 
Formation qhse - GIASE saqit_105135.pptx
Formation qhse - GIASE saqit_105135.pptxFormation qhse - GIASE saqit_105135.pptx
Formation qhse - GIASE saqit_105135.pptx
 
Cours ofppt du Trade-Marketing-Présentation.pdf
Cours ofppt du Trade-Marketing-Présentation.pdfCours ofppt du Trade-Marketing-Présentation.pdf
Cours ofppt du Trade-Marketing-Présentation.pdf
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI DẠY BUỔI 2) - TIẾNG ANH 6, 7 GLOBAL SUCCESS (2...
 
La nouvelle femme . pptx Film français
La   nouvelle   femme  . pptx  Film françaisLa   nouvelle   femme  . pptx  Film français
La nouvelle femme . pptx Film français
 
Apolonia, Apolonia.pptx Film documentaire
Apolonia, Apolonia.pptx         Film documentaireApolonia, Apolonia.pptx         Film documentaire
Apolonia, Apolonia.pptx Film documentaire
 
COURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdf
COURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdfCOURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdf
COURS SVT 3 EME ANNEE COLLEGE 2EME SEM.pdf
 
L application de la physique classique dans le golf.pptx
L application de la physique classique dans le golf.pptxL application de la physique classique dans le golf.pptx
L application de la physique classique dans le golf.pptx
 
Cours Préparation à l’ISO 27001 version 2022.pdf
Cours Préparation à l’ISO 27001 version 2022.pdfCours Préparation à l’ISO 27001 version 2022.pdf
Cours Préparation à l’ISO 27001 version 2022.pdf
 
Formation échiquéenne jwhyCHESS, parallèle avec la planification de projet
Formation échiquéenne jwhyCHESS, parallèle avec la planification de projetFormation échiquéenne jwhyCHESS, parallèle avec la planification de projet
Formation échiquéenne jwhyCHESS, parallèle avec la planification de projet
 
Les roches magmatique géodynamique interne.pptx
Les roches magmatique géodynamique interne.pptxLes roches magmatique géodynamique interne.pptx
Les roches magmatique géodynamique interne.pptx
 

Tour C++

  • 1. 8Q SHWLW WRXU GX & 'LGLHU 'RQVH] ,679 89+ GRQVH]#XQLYYDOHQFLHQQHVIU Didier DONSEZ 1995-1998 Un petit tour du C++ 1 http://krimo666.mylivepage.com/
  • 2. RPELQDLVRQ GH IRQFWLRQQDOLWpV ODQJDJH - Performances SURJUDPPDWLRQ VVWqPH ODQJDJH $'$ Concept de Généricité et de Modularité Surcharge ODQJDJH 22 Héritage Statique (simple et multiple) Spécialisation - Généralisation - Abstraction 6PDOOWDON 2EM/LVS (LIIHO 2EMHFWLYH -DYD« HW ELHQ V€U Didier DONSEZ 1995-1998 Un petit tour du C++ 2 http://krimo666.mylivepage.com/
  • 3. OD VQWD[H GH EDVH OH ODQJDJH VQWD[WH FODVVLTXH type de base (char, int, long, float, double, unsigned ....) type constructeur (array [], struct, union) opérateurs, expressions, blocs, structures de contrôle (if, switch, while, for ) fonctions (bibliothéque d'entrée/sortie) Didier DONSEZ 1995-1998 Un petit tour du C++ 3 http://krimo666.mylivepage.com/
  • 4. ([WHQVLRQ GX ODQJDJH référence QRPPDJH PXOWLSOH G XQ REMHW int a; int abis = a; VLPSOLILFDWLRQ G pFULWXUH SRXU SDUDPrWUHV SDU YDULDEOH int inc_ptr(int* i) { return ++(*i); } int b,c; c = inc_ptr(b); int inc_ref(int i) { return ++i; } c = inc_ref(b) ; surcharge de fonctions void print( int ) { ... }; void print( double ) { ... }; void print( char* ) { ... }; fonction inline inline int increment(int a) { return ++a; } #define INCREMENT(A) (++(A)) Didier DONSEZ 1995-1998 Un petit tour du C++ 4 http://krimo666.mylivepage.com/
  • 5. $SSRUW GH ODQJDJH 22 OHV FODVVHV G REMHWV encapsulation des membres, manipulation au travers des méthodes. class Entreprise { // membres int nbEmployes Employe* listePersonnel[MAX_Pers]; public: // constructeur/destructeur Entreprise(); Entreprise(Entreprise*); ˜Entreprise(); private: // méthodes void embauche(Employe*, int sal=SAL_SMIC) void debauche(Employe*); void debauche(Employe*, int primeDepart); //surcharge public: // méthodes d'opérateur Entreprise operator += (Employe* e) inline Entreprise operator -= (Employe* e) { debauche(e); return *this; } } Didier DONSEZ 1995-1998 Un petit tour du C++ 5 http://krimo666.mylivepage.com/
  • 6. 'pFODUDWLRQV ,PEULTXpHV class List { class Element { public: ... give(Obj o); }; public: insert(Obj o); }; class List { class Element { public: ... alloc(Obj o); }; public: insert(Obj o); }; Array::Element::give(Obj o) { ... } List::Element::alloc(Obj o) { ... } class Process { public: enum Status { IDLE, RUNNING }; Status st; ... }; schedule() { Process::Status st = IDLE; ... } Didier DONSEZ 1995-1998 Un petit tour du C++ 6 http://krimo666.mylivepage.com/
  • 7. $SSRUW GH ODQJDJH 22 PDQLSXODWLRQ GHV REMHWV main() { Entreprise IBM; // constructeur 1 Entreprise* Bell = new Entreprise; // ex-malloc + constructeur 1 Employe durant; Employe* p_durant = durant Employe martin; IBM.embauche(p_durant); IBM -= p_durant; Bell-embauche(p_durant); (Bell) += martin; Entreprise ATT(Bell); // constructeur 2 // instanciation au milieu du code delete Bell; // desallocateur + destructeur ATT -= p_durant; // } // en sortie de bloc // destructeur ˜Entreprise() pour IBM, ATT // destructeur ˜Employe() pour durant, martin Didier DONSEZ 1995-1998 Un petit tour du C++ 7 http://krimo666.mylivepage.com/
  • 9. MyClass() est généré par défaut mais il peut être surchargé Il est invoqué lors de la déclaration des variables locales (et paramêtres) et par l'opérateur MyClass::new() NB : MyClass(MyClass) peut être invoqué lors d'une affectation 'HVWUXFWHXU a0ODVV
  • 10. généré par défaut mais il peut être surchargé une seule fois Il est invoqué sur les variables locales (et paramêtres) à la sortie d'un bloc (ou de la fonction) et par l'opérateur MyClass::delete() Didier DONSEZ 1995-1998 Un petit tour du C++ 8 http://krimo666.mylivepage.com/
  • 12. généré par défaut mais il peut être surchargé $OORFDWHXU RSHUDWRU QHZ
  • 13. l'opérateur ::new() est l'allocateur globale il existe par défaut mais il peut être surchargé 'pVDOORFDWHXU RSHUDWRU 0ODVVGHOHWH
  • 14. généré par défaut mais il peut être surchargé 'pVDOORFDWHXU RSHUDWRU GHOHWH
  • 15. l'opérateur ::delete() est l'allocateur globale il existe par défaut mais il peut être surchargé Didier DONSEZ 1995-1998 Un petit tour du C++ 9 http://krimo666.mylivepage.com/
  • 16. RQVWUXFWHXUV 'HVWUXFWHXU $OORFDWHXU 'pVDOORFDWHXU ([HPSOH
  • 17. class Str { public: char* cs; Str() { cs=(char*)NIL; }; Str(char* cs) { this-cs=new char[strlen(cs)+1]; strcpy(this-cs,cs);}; Str(const Str s){ if(this-cs!=(char*)NIL) delete this-cs; this-cs=new char[strlen(s.cs)+1]; strcpy(this-cs,cs.s);}; ~Str() { if(this-cs!=(char*)NIL) delete this-cs; }; }; Str func(Str p){ // Str::Str(const Str) pour p Str v1; // Str::Str() pour v1 ... { Str v2(v1); // Str::Str(const Str) pour v2 Str v3 = v2; // Str::Str(const Str) pour v3 ... } // Str::~Str pour v3, v2 ... } // Str::~Str pour v1, p int main(){ Str m1(toto); // Str::Str(char*) pour m1 Str m2 = func(m1); // Str::Str(const Str) pour m2 } Didier DONSEZ 1995-1998 Un petit tour du C++ 10 http://krimo666.mylivepage.com/
  • 18. 2SpUDWHXUV Définition des Opérateurs PpWKRGHV DSSHOpHV DYHF XQH IRUPH VQWD[LTXH DOJpEULTXH class Obj; class ListObj { public: ... ListObj(); ListObj(const ListObj); ListObj operator =(const ListObj); ListObj operator +=(const ListObj); ListObj operator +=(const Obj); const Obj operator [](long); }; ListObj operator + (const ListObj, const ListObj ); Utilisation des Opérateurs ListObj l2, l3; ListObj l1(l3); // ListObj(const ListObj); // vs ListObj();l1.operator=(l3); l1 += l2; // l1.operator+=( l2 ) l1 += l3[0]; // l1.operator+=( l3.operator[](0) ) l1 = l2 + l3; // l1.operator=( operator+(l2,l3) ); Didier DONSEZ 1995-1998 Un petit tour du C++ 12 http://krimo666.mylivepage.com/
  • 19. +pULWDJHV 6LPSOH HW 0XOWLSOH OHV RQVWUXFWHXUV
  • 20. class Person { public: char* nom; Person(char* nom) { this-nom = new char[strlen(nom)+1]; strcpy(this-nom, nom); }; } class Etudiant : public Person { public: char* etude; Etudiant (char* nom, char* etu) : Person(nom) { etude = new char[strlen(nom)+1]; strcpy( etude, etu); }; } class Employe : public Person { public: int echelon; Employe(char* nom, int ech) : Person(nom), echelon(ech) {}; } class Etudiant_en_FormCont: public Etudiant, virtual public Employe { public: Etudiant_en_FormCont(char* nom, char* etu, int ech) : Etudiant(nom,etu), Employe(nom, ech) {}; } Didier DONSEZ 1995-1998 Un petit tour du C++ 13 http://krimo666.mylivepage.com/
  • 21. 0pWKRGHV 9LUWXHOOHV 0pWKRGHV QRQ 9LUWXHOOHV class Person { public: char* nom; virtual printVIRT() { cout nom;}; print() { cout nom;}; }; class Employe : public Person { public: int echelon; virtual printVIRT() { Person::printVIRT(); cout echelon; }; print() { Person::print(); cout echelon; }; print2() { Employe::print(); }; }; f(){ Employe Bill; Employe e = Bill; Person p = e; // Person p = Bill; e-printVIRT(); // Employe::printVIRT() e-print(); // Employe::print() e-print2(); // Employe::print2() p-printVIRT(); // Employe::printVIRT() (abstraction) p-print(); // Person::print() p-print2(); // Erreur de Compilation } Didier DONSEZ 1995-1998 Un petit tour du C++ 14 http://krimo666.mylivepage.com/
  • 22. +pULWDJH 0XOWLSOH HW 0pWKRGHV class Person { public: char* nom; virtual print() { cout nom;}; } class Employe : public Person { public: int echelon; virtual print() { // spécialisation Person::print(); cout echelon; }; } class Etudiant : public Person { public: char* etude; virtual print() { // spécialisation Person::print(); cout etude; }; } class Etudiant_en_FormCont: public Etudiant, virtual public Employe { public: virtual print() { Etudiant::print(); Employe::print(); }; Didier DONSEZ 1995-1998 Un petit tour du C++ 15 http://krimo666.mylivepage.com/
  • 24. pas d’instanciation possible pour ces classes class Figure { public: virtual void draw()=0; }; class Circle : public Figure { virtual void draw() { ... }; }; Figure fig; // KO Circle circle; // OK 5HPDUTXH GpILQLWLRQ RSWLRQHOOH GH Figure::draw() Didier DONSEZ 1995-1998 Un petit tour du C++ 16 http://krimo666.mylivepage.com/
  • 25. RQWU{OH G $FFHV , 'pILQLWLRQ
  • 26. Private (défaut) VHXOHPHQW PpWKRGHV PHPEUHV LQLWLDOLVHXUV GH OD FODVVH PpWKRGHV IULHQG Protected HQ SOXV PpWKRGHV PHPEUHV G XQH FODVVH GpULYpH Public WRXWHV PpWKRGHV RX IRQFWLRQV Didier DONSEZ 1995-1998 Un petit tour du C++ 17 http://krimo666.mylivepage.com/
  • 27. RQWU{OH G $FFHV ,, 8WLOLVDWLRQ
  • 28. class Base { class Derive : public Base { private: int d(); int a; protected: protected: int e; int b(); public: public: int f; int c; }; private: int g(); }; Base::g() { Derive::g() { f(Base bs, Derive a++; // OK a++; // OK dr){ b(); // OK b(); // OK bs.a++; // Error c++; // OK c++; // OK bs.b(); // Error } bs.c++; // OK d(); // OK e++; // OK dr.d(); // Error f++; // OK dr.e++; // Error } dr.f++; // OK } Didier DONSEZ 1995-1998 Un petit tour du C++ 18 http://krimo666.mylivepage.com/
  • 30. class Base { class Derive class DD : Derive { private: int a; : XXXXX Base { fDD(Derive); protected: int b(); int d(); }; public: int c; protected int e; private: int g(); public: int f; }; }; XXXXX = public XXXXX = protected XXXXX = private DD::fDD(Derive dr){ DD::fDD(Derive dr){ DD::fDD(Derive dr){ dr.a++; // Error dr.a++; // Error dr.a++; // Error dr.b(); // OK dr.b(); // OK dr.b(); // Error dr.c++; // OK dr.c++; // OK dr.c++; // Error } } } f(Derive dr){ f(Derive dr){ f(Derive dr){ dr.a++; // Error dr.a++; // Error dr.a++; // Error dr.b(); // Error dr.b(); // Error dr.b(); // Error dr.c++; // OK dr.c++; // Error dr.c++; // Error } } } la classe Derive rend public la classe Derive rend public la classe Derive le contrôle d'accès le contrôle d'accès ne rend pas public de sa super-classe de sa super-classe le contrôle d'accès à tous uniquement de sa super-classe à ses sous classes et aux friends Didier DONSEZ 1995-1998 Un petit tour du C++ 19 http://krimo666.mylivepage.com/
  • 32. Friend IRQFWLRQ DPLH FODVVH DPLH DXWRULVH OHV DFFqV SULYDWH HW SURWHFWHG DX[ IRQFWLRQV QRQ PHPEUHV class Matrix { Vector Diagonal(); }; class Vector { private: friend class Matrix; friend Matrix multiple(Matrix,Vector); int size; }; Vector Matrix::Diagonal() { .. = size; } Matrix multiple(Matrix m,Vector v) { .. = size; } Didier DONSEZ 1995-1998 Un petit tour du C++ 20 http://krimo666.mylivepage.com/
  • 33. RQVW class Obj { friend g(const Obj); int i; public: f(); f_CONST() const; }; g(const Obj* o) { cout o-i; // OK o-i++; // Erreur ((Obj*)o)-i++; // OK } main() { Obj* o = new Obj; const Obj* oc = o; // OK Obj* onc = oc; // Erreur Obj* onc2 = (Obj*)o; // OK o-f(); // Erreur o-f_CONST(); // OK } Didier DONSEZ 1995-1998 Un petit tour du C++ 21 http://krimo666.mylivepage.com/
  • 34. *pQpULFLWp FODVVHV SDUDPpWUpHV Déclaration template class T class List { struct Element { public: T* value; Element* next; }; Element* first; public: ListT(); ListT(const ListT); ListT operator =(const ListT); ListT operator +=(const ListT); ListT operator +=(const T); const T operator [](long); }; ListT operator + (const ListT, const ListT ); Utilisation Listint li; li += 1; cout li[0]; Listdouble ld; ld += 3.1416; ListEmploye mcrosft; mcrosft += new Employe(“Bill”); ListPerson wldcny; wldcny += mcrosft; Didier DONSEZ 1995-1998 Un petit tour du C++ 22 http://krimo666.mylivepage.com/
  • 35. ([FHSWLRQV Traitement des erreurs dans un langage séquentiel err_t fn( res_t r ) { ... if(...){ r = result; return OK; } else return KO; } for(i=0; (err=fn(i))==OK iMAX; i++ ) {} if(err==KO) { traitement d’erreur } Execptions C++: mécanisme alternatif de traitement des erreurs “synchrones” • simplification du code de l’application QRWDQPHQW DX QLYHDX GHV FRQVWUXFWHXUV • efficacité SDUIRLV VL 0$; JUDQG • récupération d’une erreur “levée” dans une fonction de bibliothèque Didier DONSEZ 1995-1998 Un petit tour du C++ 23 http://krimo666.mylivepage.com/
  • 36. ([FHSWLRQV 0pFDQLVPH Définition class MathError{}; class DivideZero : MathError {}; class Overflow : MathError { char* _str; Overflow(char* str); }; double add(double d1; double d2) { ... if(...) throw Overflow(“+”); } f(){ try { add(maxdouble, maxdouble); // raise Overflow } catch(DivideZero) { // traitement pour DivideZero } } g(){ try { f(); } catch(Overflow o) { cerr “Overflow sur “ o._str; exit(); } catch(MathError) { // traitement pour MathError et autres dérivés }} Didier DONSEZ 1995-1998 Un petit tour du C++ 24 http://krimo666.mylivepage.com/
  • 37. 0DQTXHV GDQV OH 5DPDVVH 0LHWWH 0pWD 0RGqOH 'QDPLF %LQGLQJ 0XOWL $FWLYLWp WKUHDG -DYD RX WDVN $'$
  • 38. Didier DONSEZ 1995-1998 Un petit tour du C++ 25 http://krimo666.mylivepage.com/
  • 39. OHV 5DPDVVHV 0LHWWH *DUEDJH ROOHFWRU
  • 40. Destruction explicite par l'opérateur de désallocation delete() 6PDOOWDON -DYD Destruction implicite quand l'instance n'est plus référencée par aucune autre instance QpFHVVLWH XQ 5DPDWWH 0LHWWH c.a.d. récupération des instances inaccessibles Techniques: Compteur de référence, Mark-and-Sweep, Incrémentale ... ELEOLRWKpTXH GH 5DPDVVHV 0LHWWH par héritage avec des techniques différentes classes par classes Didier DONSEZ 1995-1998 Un petit tour du C++ 26 http://krimo666.mylivepage.com/
  • 41. 5DPDVVHV 0LHWWH H[HPSOH RPSWHXU GH 5pIpUHQFH
  • 42. template class CGC class Ref { CGC* ptr; public: CGC* operator =(const CGC* t) { if(ptr) ptr-decref(); ptr = t; t-incref(); return ptr; }; }; class ObjectGC { int cpt; ObjectGC() : cpt(0) {} virtual ˜ObjectGC() {}; public: void incref() { cpt++; }; void decref() { if(--cpt==0) delete this; }; }; class MyClass : public ObjectGC { ... }; RefMyClass ref1 = new MyClass; // cpt==1 RefMyClass ref2 = ref1; // cpt==2 ref1 = 0; // cpt==1 ref2 = ref3; // cpt==0 Destruction effective Didier DONSEZ 1995-1998 Un petit tour du C++ 27 http://krimo666.mylivepage.com/
  • 43. 0pWD ODVVHV RQVWUXFWLRQ GQDPLTXH GX VFKpPD Implantation difficile dans une approche compilé $SSOLFDWLRQV ,$ 'QDPLF %LQGLQJ $MRXW GHV ELEOLRWKqTXHV G REMHWV DX 5XQWLPH Dépend de système mais reste compliqué Objective-C (GNU) utilisé dans NeXTStep, Java dans la JVM $SSHO GH PpWKRGHV GLVWDQWHV RPC - OO, Corba 0XOWL $FWLYLWp 3DV GH VSpFLILFDWLRQ GH RURXWLQHV RX GH 7DFKHV GDQV OH ODQJDJH %XW 2EMHWV UpDFWLIV Didier DONSEZ 1995-1998 Un petit tour du C++ 28 http://krimo666.mylivepage.com/
  • 44. Solution: encapsuler des librairies système (pthread POSIX) si le système le permet Didier DONSEZ 1995-1998 Un petit tour du C++ 29 http://krimo666.mylivepage.com/
  • 45. RQFOXVLRQ *URV SRLQW IRUW O (IILFDFLWp GX 8Q VXU HQVHPEOH GH OD VQWD[H GX Apprentissage plus facile pour un programmeur C Migration incrémentale des applications C vers le C++ ([WHQVLEOH YLD GHV ELEOLRWKqTXHV Mais malheureusement très peu standardisée 8Q VWDQGDUG GH IDLW SRXU OH *pQLH /RJLFLHO grand nombre de compilateurs et AGL (public ou payant) choisi par l'OMG (Object Management Group - i.e. CORBA) SRXU OHV 6*'% 22 choisi par l'ODMG (Object Database Management Group) (3(1'$17 6XELW XQH WUqV IRUWH FRQFXUUHQFH GH OD SDUW GH -$9$ Didier DONSEZ 1995-1998 Un petit tour du C++ 30 http://krimo666.mylivepage.com/
  • 46. %LEOLRJUDSKLH (OOLV HW 6WURXVWUXS 7KH $QQRWDWHG 5HIHUHQFH 0DQXDO $GGLVRQ:HOOH 3XEOLVKLQJ RPSDQ La sainte bible du developpeur C++ (en anglais) 6WURXVWUXS /H ODQJDJH une introduction pédagogique (en anglais et en français) 0DVVLQL /HV ODQJDJHV j 2EMHWV un bon panorama des langages objets (syntaxte et implantation) comp.object comp.std.c++ les derniers potins, les trucs, les FAQ, des tutoriaux ... Didier DONSEZ 1995-1998 Un petit tour du C++ 31 http://krimo666.mylivepage.com/