CS 250 Computer Programming and Problem Solving - FALL 1998 |
---|
[ Home | Syllabus | Notes | Glossary | CS250 WEB Version Home Page ]
Sections of chapter 3 to be deferred:
Chapter 3: Misc Topics
"const" modifier
Description | const is used to
tell the compiler that the thing being modified is constant (that is unchangeable) this
information is used by the compiler to protect data from being changed. It can be used to modify:
|
Syntax |
|
Examples |
|
Tips |
|
Friends
Description |
|
Syntax | friend function-type function-ID(parameter-list) |
Example (full example here) |
#include <math.h> friend float distance(Coordinate p1, Coordinate p2) { float deltaX = p1.x - p2.x; float deltaY = p1.y - p2.y; return sqrt(deltaX*deltaX + deltaY*deltaY); // sqrt in math.h } |
Tips |
|
Go over complete example to show:
Overloading Functions
Description |
|
Syntax | no special syntax required |
Example | float add(float a, float b) { return a + b; } int add(int a, int b) { return a + b; } |
Tips |
|
Overloading I/O Stream Operators
Description |
|
Syntax | friend ostream & operator <<
(ostream & os, const objectType objectID); friend istream & operator >> (istream & is, objectType objectID); |
Example |
// in the class definition in the header file
"Coordinate.h" .... friend ostream & operator << (ostream & oStream, const Coordinate & aPoint); friend istream & operator >> (istream & iStream, Coordinate & aPoint); // in the
function definition file "Coordinate.cpp" istream & operator >> (istream & iStream,
Coordinate & aPoint) { // to use, just do the usual I/O statement (in main.cpp) |
Tips |
|
Overloading I/O Stream Operators (Safer Example)
Overload I/O Safer Example for Coordinate
Description |
|
Example (click here for full example) |
// in the class defintion in the header file
"Coordinate.h" .... friend ostream & operator << (ostream & oStream, const Coordinate & aPoint); //NOTE: doesn't need to be friend - see definition below istream & operator >> (istream & iStream, Coordinate & aPoint); // in the function definition
file "Coordinate.cpp" istream & operator >> (istream & iStream,
Coordinate & aPoint) { // to use, just do the usual I/O statement (in main.cpp) |
Tips |
|