This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
in204:tds:sujets:td1:part2 [2019/09/23 16:05] bmonsuez [Question n° 3] |
in204:tds:sujets:td1:part2 [2022/11/18 10:50] (current) |
||
|---|---|---|---|
| Line 104: | Line 104: | ||
| </code> | </code> | ||
| - | Dans les dernières versions de C++, il est possible de faire appel à un constructeur déjà défini. Ainsi, le code peut se simplifier comme suit : | + | Depuis la version C++11, il est possible de faire appel à un constructeur déjà défini. Ainsi, le code peut se simplifier comme suit : |
| <code cpp> | <code cpp> | ||
| Line 111: | Line 111: | ||
| ... | ... | ||
| explicit MyCounter(uint theMaxValue): | explicit MyCounter(uint theMaxValue): | ||
| - | this((uint)0, theMaxValue) | + | MyCounter((uint)0, theMaxValue) |
| // Effectue un appel au constructeur MyCounter(uint, uint) | // Effectue un appel au constructeur MyCounter(uint, uint) | ||
| {} | {} | ||
| Line 120: | Line 120: | ||
| </code> | </code> | ||
| + | La fonction ''useObjectA()'' peut désormais s'écrire comme suit: | ||
| + | |||
| + | <code cpp> | ||
| + | void useObjectA() { | ||
| + | MyCounter Counter1(2); | ||
| + | MyCounter Counter2(4) | ||
| + | for(unsigned i = 0; i <= 5; i++) { | ||
| + | std::cout | ||
| + | << "Valeur des compteurs (" << Counter1.counter | ||
| + | << ", " << Counter2.counter << ")" << std::endl; | ||
| + | Counter1.increment(); | ||
| + | Counter2.increment(); | ||
| + | } | ||
| + | } | ||
| + | </code> | ||
| </hidden> | </hidden> | ||
| ==== Question n° 4 ==== | ==== Question n° 4 ==== | ||
| Proposer enfin un constructeur de recopie qui permet de créer un nouveau compteur étant la copie d’un compteur passé en paramètre. | Proposer enfin un constructeur de recopie qui permet de créer un nouveau compteur étant la copie d’un compteur passé en paramètre. | ||
| - | + | ||
| + | <hidden Correction> | ||
| + | |||
| + | Le constructeur de recopie se définit simplement comme suit : | ||
| + | |||
| + | <code cpp> | ||
| + | struct MyCounter | ||
| + | { | ||
| + | MyCounter(const MyCounter& anotherCounter): | ||
| + | counter(anotherCounter.counter), | ||
| + | max(anotherCounter.max) | ||
| + | {} | ||
| + | }; | ||
| + | </code> | ||
| + | |||
| + | </hidden> | ||