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:00] bmonsuez [Question n° 2] |
in204:tds:sujets:td1:part2 [2022/11/18 10:50] (current) |
||
|---|---|---|---|
| Line 87: | Line 87: | ||
| proposé ces solutions. | proposé ces solutions. | ||
| + | <hidden Correction> | ||
| + | |||
| + | Il est possible d'ajouter des constructeurs spécialisés à la classe ''MyCounter'', nous proposons les deux constructeurs suivants : | ||
| + | |||
| + | <code cpp> | ||
| + | struct MyCounter | ||
| + | { | ||
| + | ... | ||
| + | explicit MyCounter(uint theMaxValue): | ||
| + | counter(0), max(theMaxValue) | ||
| + | {} | ||
| + | MyCounter(uint theCounter, uint theMaxValue): | ||
| + | counter(theCounter), max(theMaxValue) | ||
| + | {} | ||
| + | }; | ||
| + | </code> | ||
| + | |||
| + | 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> | ||
| + | struct MyCounter | ||
| + | { | ||
| + | ... | ||
| + | explicit MyCounter(uint theMaxValue): | ||
| + | MyCounter((uint)0, theMaxValue) | ||
| + | // Effectue un appel au constructeur MyCounter(uint, uint) | ||
| + | {} | ||
| + | MyCounter(uint theCounter, uint theMaxValue): | ||
| + | counter(theCounter), max(theMaxValue) | ||
| + | {} | ||
| + | }; | ||
| + | </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> | ||
| ==== 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> | ||