1k likes | 1.22k Views
User-Defined Classes. Chapter 10. 10.1 Class Definition. int, float, char are built into C+ Declare and use int x = 5; Create user defined data types+ Extensive use throughout remainder of course Counter class will introduce the concept counter.h counter class definitions
E N D
User-Defined Classes Chapter 10
10.1 Class Definition • int, float, char are built into C+ • Declare and use • int x = 5; • Create user defined data types+ • Extensive use throughout remainder of course • Counter class will introduce the concept • counter.h counter class definitions • Define the class in the .h file
User Defined Types • Define what data we want in the class • data elements of the class are private • Create the functionality to operate on the data • class member functions access data • We have created a new data type not known to the compiler
Counter.h // FILE: Counter.h // COUNTER CLASS DEFINITION #ifndef COUNTER_H #define COUNTER_H class counter { public: counter (); counter (int);
Counter.h // SET COUNTER VALUE void setCount (int); // INCREMENT COUNTER void increment (); // DECREMENT COUNTER void decrement (); // RETURN CURRENT COUNTER VALUE int getCount () const;
Counter.h // RETURN MAXIMUM COUNTER VALUE int getMaxValue () const; private: // Data Members (Attributes)... int count; int maxValue; }; #endif
Compiler Directives • Prevent multiple definitions #ifndef COUNTER_H #define COUNTER_H #endif • 1st the #ifndef tests to see if COUNTER_H has been defined • If not the 2nd line #define defines the content • If defined skips to the #endif
Using the counter Class • Driver program CounterTest.cpp will help us see how the Counter Class is used • Must #include “Counter.h” because our class definitions are contained in it. • Change this view based on our compiler • #include “Counter.cpp”
CounterTest.cpp // File: CounterTest.cpp // Test the counter class #include <iostream> #include "counter.h" #include "counter.cpp" using namespace std; int main() {
CounterTest.cpp counter c1; counter c2(10); // Test setValue, increment, decrement, and // accessValue functions. c1.setCount(50); c1.decrement(); c1.decrement(); c1.increment(); cout << "Final value of c1 is " << c1.getCount() << endl;
CounterTest.cpp c2.increment(); c2.increment(); c2.decrement(); cout << "Final value of c2 is " << c2.getCount() << endl; return 0; }
10.2 Class Implementation • Counter.cpp implementation details • Hidden from users (details) • Scope resolution operator • :: prefix for each member function • Informs the compiler that the function is a member of the class • Class member functions can access all class data members • Avoid using member functions inside member functions
Constructors • Two special member functions • Same name as class name • Constructor executes each time an object of type counter is declared • counter mike; • Initializes object • Types • Default • Class
Constructors • Default Constructor • Used when no arguments passed as part of the declaration • Class Constructor • Used when arguments are passed as part of the declaration • Constructors do NOT specify a return type
Member Functions • Member functions that modify data are • setValue • increment • decrement • Member functions that retrieve data are • getvalue • getmaxvalue • Const; at the end of the function means no data changes by the function
Counter.cpp // File: counter.cpp // Counter class implementation #include "counter.h" #include <iostream> #include <climits> using namespace std; // Default constructor counter::counter() { count = 0; maxValue = INTMAX; }
Counter.cpp // Constructor with argument counter::counter(int mVal) { count = 0; maxValue = mVal; } // Increment counter void counter::increment() { if (count < maxValue) count++;
Counter.cpp else cerr << "Counter overflow. Increment ignored." << endl; } // Decrement counter void counter::decrement() { if (count > 0) count--; else cerr << "Counter underflow. Decrement ignored." << endl; }
Counter.cpp // Set counter value void counter::setCount(int val) { if (val >= 0 && val <= maxValue) count = val; else cerr << "New value is out of range. Value not changed." << endl; } // Set maximum counter value void counter::setMaxValue(int val) {
Counter.cpp if (val >= 0 && val <= INTMAX) maxValue = val; else cerr << "New maxValue is out of range -- not changed." << endl; } // Return current counter value int counter::getCount() const { return count; }
Counter.cpp // Return maximum counter value int counter::getMaxValue() const { return maxValue; }
10.3 Summary of Rules for Use of Classes and Objects • Class Instance • counter c1; • Creates an instance of the counter class (object) • Default constructor invoked • Allocates space in memory for object • Similar to other data type declarations • int value; • Space in memory allocated for a data type int
Private vs Public • Public member functions allow users to operate on the counter object c1 • May have private member functions • If member functions need to call another function not part of the class it should be private • Use care when defining public access • Users of a class are clients • Class sometimes referred to asthe server
Syntax Form: class className { public: List all public data and functions private: List all private data and functions };
Comparing struct and classes • struct & class define a data type • Collection of related elements • Prototype declarations • Three levels of access control • Public • Private • Protected (not covered) • Major difference default access opposite • class private - struct public
Function Overloading & Polymorphism • Functions with the same name is called function overloading • Polymorphism is what allows functions with the same name to do different things based on its arguments
10.4 Classes as Operands and Arguments • Assignment operator can be used • Others must be re-defined (Chap 11) • Operator Overloading • Use C& ob1 as formal reference argument • Use const C& ob1 to specify object can’t be modified by a function • Efficiency issues
CompareCounter c1.compareCounter (c2) ; or c2.compareCounter (c1); int counter::compareCounter (const counter& aCounter) const { int result; if (value <= aCounter.count) result = -1; else if (value == aCounter.count) result = 0; else result = 1; return result; }
10.5 A Fraction Class • Design of Fraction Class • Data represents Numerator • Data represents Denominator • FractionTest.cpp • Fraction.cpp
FractionTest.cpp // File: fractiontest.cpp // Tests the fraction class. #include <iostream> #include "fraction.h" #include "fraction.cpp" using namespace std; int main() { fraction f1, f2; fraction f3;
FractionTest.cpp // Read two fractions cout << "Enter 1st fraction: " << endl; f1.readFrac(); cout << "Enter 2nd fraction: " << endl; f2.readFrac(); if (f1 == f2) cout << "same" << endl; // Display results of fraction arithmetic f3 = f1.multiply(f2); f1.displayFrac(); cout << " * "; f2.displayFrac(); cout << " = ";
FractionTest.cpp f3.displayFrac(); cout << endl; f3 = f1.divide(f2); f1.displayFrac(); cout << " / "; f2.displayFrac(); cout << " = "; f3.displayFrac(); cout << endl; //f3 = f1.add(f2); f3 = f1 + f2; f1.displayFrac(); cout << " + "; f2.displayFrac(); cout << " = "; f3.displayFrac(); cout << endl;
FractionTest.cpp f3 = f1.subtract(f2); f1.displayFrac(); cout << " - "; f2.displayFrac(); cout << " = "; f3.displayFrac(); cout << endl; return 0; }
Fraction.cpp // File: Fraction.cpp // Fraction class implementation #include "fraction.h" #include <iostream> using namespace std;
Fraction.cpp // Member functions // Constructors fraction::fraction() { num = 0; denom = 0; } fraction::fraction(int n) { num = n; denom = 1; }
Fraction.cpp fraction::fraction(int n, int d) { num = n; denom = d; } // Set numerator and denominator void fraction::setNum(int n) { num = n; }
Fraction.cpp void fraction::setDenom(int d) { denom = d; } // Multiply fractions fraction fraction::multiply(const fraction& f) { fraction temp(num * f.num, denom * f.denom); return temp; }
Fraction.cpp // Divide fractions fraction fraction::divide(const fraction& f) { fraction temp(num * f.denom, denom * f.num); return temp; } // Add fractions fraction fraction::add(const fraction& f) { fraction temp(num * f.denom + f.num * denom, denom * f.denom); return temp; }
Fraction.cpp // Subtract Fractions fraction fraction::subtract(const fraction& f) { fraction temp(num * f.denom - f.num * denom, denom * f.denom); return temp; }
Fraction.cpp // Read a fraction void fraction::readFrac() { char slash; // storage for / do { cout << "Enter numerator / denominator: "; cin >> num >> slash >> denom; } while (slash != '/'); }
Fraction.cpp // Display a fraction void fraction::displayFrac() const { cout << num << '/' << denom; } // Accessors int fraction::getNum() const { return num; }
Fraction.cpp fraction fraction::operator + (const fraction& f2) // IN: right-operand { fraction temp(num * f2.denom + f2.num * denom, denom * f2.denom); return temp; } bool fraction::operator == (const fraction& f) { return(num == f.num && denom == f.denom); }
Fraction.cpp int fraction::getDenom() const { return denom; }
10.6 Circle Class • Data members to represent x & y coordinates • Radius • Color • Area • Perimeter • See specification on page 509
Circle.h // File circle.h // Circle class definition #ifndef CIRCLE_H #define CIRCLE_H class circle { public: // enumeration type enum color {black, blue, green, cyan, red, magenta, brown, lightgray, nocolor};
Circle.h // Member Functions // constructor circle(); // Set center coordinates void setCoord(int, int); // Set radius void setRadius(float); // Set color void setColor(color);
Circle.h // Compute the area void computeArea(); // Compute the perimeter void computePerimeter(); // Display attributes void displayCircle() const;
Circle.h // accessor functions int getX() const; int getY() const; float getRadius() const; color getColor() const; float getArea() const; float getPerimeter() const;
Circle.h private: // Data members (attributes) int x; int y; float radius; color cColor; float area; float perimeter; }; #endif // CIRCLE_H
CircleTest.cpp // File circletest.cpp // Tests the Circle class #include "circle.h" #include "circle.cpp" #include <iostream> using namespace std; int main() {