TopicsDesign HeuristicsDesign Heuristics continuedReference parametersQuadratic Equation ExampleWho supplies memory, where’s copy?ExamplesAnother ExampleYet another exampleParameter Passing: const-referenceCount # occurrences of “e”General rules for ParametersStreams for reading filesInput file stream: Note similarity to cinFind longest word in file (most letters)Maximal and Minimal ValuesRead values, find largest (smallest)What about if ints are strings?Using classes to solve problemsComplete the code belowTwo problemsStringSet and WordIteratorSee setdemo.cppClasses: From Use to ImplementationAnatomy of the Dice classThe header file dice.hThe header file is a class declarationFrom interface to use, the class DiceHeader file as InterfaceWilliam H. (Bill) Gates, (b. 1955)From Interface to ImplementationImplementation, the .cpp fileMore on method implementationUnderstanding Class ImplementationsClass Implementation HeuristicsBuilding Programs and ClassesA Computer Science Tapestry6.1TopicsDecompositionParameter passingReading and writing from filesDesigning classesReadingChapter 6AssignmentBiorhythmsCD ReaderA Computer Science Tapestry6.2Design HeuristicsMake each function or class you write as single-purpose as possibleAvoid functions that do more than one thing, such as reading numbers and calculating an average, standard deviation, maximal number, etc.,•If source of numbers changes how do we do statistics?•If we want only the average, what do we do?Classes should embody one concept, not several. The behavior/methods should be closely relatedThis heuristic is called Cohesion, we want functions and classes to be cohesive, doing one thing rather than severalEasier to re-use in multiple contextsA Computer Science Tapestry6.3Design Heuristics continuedFunctions and classes must interact to be usefulOne function calls anotherOne class uses another, e.g., as the Dice::Roll() function uses the class RandGenKeep interactions minimal so that classes and functions don’t rely too heavily on each other, we want to be able to change one class or function (to make it more efficient, for example) without changing all the code that uses itSome coupling is necessary for functions/classes to communicate, but keep coupling looseChange class/function with minimal impactA Computer Science Tapestry6.4Reference parametersIt’s useful for a function to return more than one valueFind roots of a quadraticGet first and last name of a userFunctions are limited to one return valueCombine multiple return values in object (create a class)Use reference parameters to send values back from function•Values not literally returned•Function call sends in an object that is changed Sometimes caller wants to supply the object that’s changedstring s = ToLower("HEllO") // return type?string s = "HeLLo";ToLower(s); // return type?A Computer Science Tapestry6.5Quadratic Equation Examplevoid Roots(double a, double b, double c, double& root1, double& root2);// post: root1 and root2 set to roots of// quadratic ax^2 + bx + c// values undefined if no roots exist int main(){ double a,b,c,r1,r2; cout << "enter coefficients "; cin >> a >> b >> c; Roots(a,b,c,r1,r2); cout << "roots are " << r1 << " " << r2 << endl; return 0;}A Computer Science Tapestry6.6Who supplies memory, where’s copy?void Roots(double a, double b, double c, double& root1, double& root2);// post: root1 and root2 set to roots of// quadratic ax^2 + bx + c// values undefined if no roots exist For value parameter, the argument value is copied into memory that “belongs” to parameterFor reference parameter, the argument is the memory, the parameter is an alias for argument memorydouble x, y, w, z;Roots(1.0, 5.0, 6.0, x, y);Roots(1.0, w, z, 2.0, x); // no good, why?A Computer Science Tapestry6.7ExamplesWhat’s prototype for a function that rolls two N-sided dice Y times and returns the number of double 1’s and double N’sHow many input parameters?How many values returned? (reference parameters)Return type of function?Name of function and parameters?void DoubleCount(int sides, int rollCount, int& snakeEyeCount, int& boxCarCount);// pre: sides > 0, rollCount > 0// post: returns # double 1’s (snakeEyeCount)// returns # double N’s N=sides(boxCarCount)A Computer Science Tapestry6.8Another ExampleWhat’s prototype for a function that returns the number of hours, minutes, and seconds in N seconds?Number of input parameters?Number of output parameters?void SecondsToHours(int& seconds, int& hours, int& minutes);// pre: seconds > 0// post: converts to hours/minutes/seconds, and// returns values in three parameters// Note: seconds is in/out parameterA Computer Science Tapestry6.9Yet another exampleWhat’s prototype for a function that returns the number of Saturdays and the number of Sundays in a year?How many input parameters?How many output parameters?Name of function and parameters?void SatSunCount(int year, int& saturdayCount, int& sundayCount);//post: returns # saturdays and sundays in year// via corresponding parametersA Computer Science Tapestry6.10Parameter Passing: const-referenceWhen parameters pass information into a function, but the object passed doesn’t change, it’s ok to pass a copyPass by value means pass a copyMemory belongs to parameter, argument is copiedWhen parameter is altered, information goes out from the function via a parameter, a reference parameter is usedNo copy is made when passing by referenceMemory belongs to argument, parameter is aliasSometimes we want to avoid the overhead of making the copy, but we don’t want to allow the argument to be changed (by a malicious function, for example)const-reference parameters avoid copies, but cannot be changed in the functionA Computer Science Tapestry6.11Count # occurrences of “e”Look at every character in the string, avoid copying the stringint LetterCount(const string& s, const string& letter)// post: return number of occurrences of letter in s{ int k, count = 0, len = s.length(); for(k=0; k < len; k++) { if (s.substr(k,1) == letter) { count++; } } return count;} Calls below are legal (but won’t be if just
View Full Document