troll batul how might you model a battle between two
play

troll batul How might you model a battle between two trolls? How - PowerPoint PPT Presentation

CSCI261 Lecture 23: Passing by Reference, Objects and Memory troll batul How might you model a battle between two trolls? How might you model a battle between two trolls? Define and describe trolls (attributes, behavior) Describe the battle


  1. CSCI261 Lecture 23: Passing by Reference, Objects and Memory troll batul

  2. How might you model a battle between two trolls?

  3. How might you model a battle between two trolls? Define and describe trolls (attributes, behavior) Describe the battle process (to the death!) Define who wins (who is left standing)

  4. Declaring functions in external files

  5. Header & Implementation Files volume.h #include <cstdlib> #include <iostream> #pragma once #include <string> #include “volume.h” int volume(int h, int w, int d); using namespace std; int main() { // ... cout << "The volume is " << volume(20, 30, 40); volume.cpp return 0; #include “volume.h” } int volume(int h, int w, int d) { return h * w * d; }

  6. Header & Implementation Files Header file (.h) contains the function prototypes. Implementation file (.cpp) contains the definitions.

  7. Header & Implementation FIles ship.h object files int speed(int thrust); (compile) coolgame.exe ship.cpp int speed(int thrust) { (link) 1010 return thrust * 10; 0010 } 0010 1010 main.cpp (compile) #include “ships.h” 0 main int main() { // cool stuff }

  8. Passing arguments by reference

  9. What? Why? Arguments are passed by value... int free_beer(int beers); f()’s beers main()’s beers int main() { 10 int beers(10); cout << beers; a copy is made 10 10 cout << free_beer(beers); cout << beers; // ... passed to f() 10 } 10 f()’s beers is 10 int free_beer(int beers) { cout << beers; 0 beers = 0; cout << beers; 0 return beers; }

  10. ...or by reference Your new friend: & f()’s beers main()’s beers int free_beer(int& beers); int main() { 10 int beers(10); cout << beers; 10 cout << free_beer(beers); // ... } 10 int free_beer(int& beers) { cout << beers; 0 beers = 0; cout << beers; return beers; 0 }

  11. void makeZero(int n) { void makeZero(int &n) { n = 0; n = 0; } } x x 3 3 makeZero(x); makeZero(x); the value of x is “copied” and passed to makeZero as n a reference to x itself is passed to makeZero as n makeZero makeZero n n 3 3 n n 0 0 x x 3 0

  12. Troll fred(“Fur-red”); MEMORY fred name => “Fur-red” height => 20 weight =>376 fred

  13. What? Huh? In general, always pass objects by reference.

  14. Homework • Read Etter 5.3 troll batul • Complete 29_trollBattle

Recommend


More recommend