« Programmation C++/Les références » : différence entre les versions

Contenu supprimé Contenu ajouté
DannyS712 (discussion | contributions)
m <source> -> <syntaxhighlight> (phab:T237267)
Ligne 10 :
 
=== Déclaration ===
<sourcesyntaxhighlight lang="cpp">
type& identificateur=variable;
ou
type& identificateur(variable);
</syntaxhighlight>
</source>
 
=== Sémantique ===
Ligne 20 :
 
=== Exemple de programme ===
<sourcesyntaxhighlight lang="cpp">
#include <iostream>
using namespace std;
Ligne 41 :
return 0;
}
</syntaxhighlight>
</source>
 
==== Exécution ====
Ligne 63 :
 
'''Exemple :'''
<sourcesyntaxhighlight lang="cpp">
 
class Retour
Ligne 80 :
}
 
</syntaxhighlight>
</source>
 
== Les références et leur lien avec les pointeurs ==
Ligne 91 :
Faites une fonction dont la déclaration sera <code>void échanger(int & a, int & b)</code> qui devra échanger les deux valeurs.
{{Boîte déroulante|titre = Solution|contenu=
<sourcesyntaxhighlight lang = "cpp">
void échanger(int & a, int & b)
{
Ligne 98 :
b = c;
}
</sourcesyntaxhighlight>}}
 
=== Exercice 2 ===
Ligne 118 :
Voici un exemple de fonction récursive qui ne répond pas à la consigne d'avoir une déclaration int factorielle (int & n) et qui par conséquent ne peut être qualifiée de solution à l'exercice 2 :
 
<sourcesyntaxhighlight lang = "cpp">
#include <iostream>
using namespace std;
Ligne 131 :
cout << "resultat : " << y << endl;
}
</syntaxhighlight>
</source>
 
Une autre solution est (mais la fonction retourne factoriel n, pas n) :
 
<sourcesyntaxhighlight lang = "cpp">
#include <iostream>
using namespace std;
Ligne 150 :
cout << "resultat : " << y << endl;
}
</syntaxhighlight>
</source>
Une autre solution :
<sourcesyntaxhighlight lang = "cpp">
#include <iostream>
 
Ligne 182 :
}
 
</syntaxhighlight>
</source>
}}
 
Ligne 191 :
 
==== Cas 1 ====
<sourcesyntaxhighlight lang = "cpp">
int b = n;
int & ref = b;
</syntaxhighlight>
</source>
 
==== Cas 2 ====
<sourcesyntaxhighlight lang = "cpp">
int x=5;
int & var = x;
</syntaxhighlight>
</source>
 
==== Cas 3 ====
<sourcesyntaxhighlight lang = "cpp">
int n = 2;
int & ref = n;
if(*(ref) == 2) ref++; //ceci provoque une erreur car ref n'est pas un pointeur
</syntaxhighlight>
</source>
 
==== Cas 4 ====
<sourcesyntaxhighlight lang = "cpp">
#include <iostream>
using namespace std;
Ligne 217 :
cout << a << endl;
}
</syntaxhighlight>
</source>
 
==== Cas 5 ====
<sourcesyntaxhighlight lang = "cpp">
int b = 2;
int ref& = b;
</syntaxhighlight>
</source>
 
==== Solution ====
Ligne 237 :
 
==== Cas 1 ====
<sourcesyntaxhighlight lang = "cpp">
#include <iostream>
using namespace std;
Ligne 250 :
cout << ref2 << " " << ref1 << endl;
}
</syntaxhighlight>
</source>
 
{{Boîte déroulante|titre = Solution|contenu = 6 -4}}