Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14 More About Classes. CS 1410 - SJAllan Chapter 14 2 Instance and Static Members Instance variable:  A member variable in a class  Each object.

Similar presentations


Presentation on theme: "Chapter 14 More About Classes. CS 1410 - SJAllan Chapter 14 2 Instance and Static Members Instance variable:  A member variable in a class  Each object."— Presentation transcript:

1 Chapter 14 More About Classes

2 CS 1410 - SJAllan Chapter 14 2 Instance and Static Members Instance variable:  A member variable in a class  Each object has its own copy static variable:  One variable shared among all objects of a class static member function:  Can be used to access static member variable  Can be called before any objects are defined

3 CS 1410 - SJAllan Chapter 14 3 Member (Instance)Variables Object W1, W2

4 CS 1410 - SJAllan Chapter 14 4 Member Variable is Static

5 CS 1410 - SJAllan Chapter 14 5 Budget.h – Program #ifndef BUDGET_H #define BUDGET_H class Budget {private: static double corpBudget; double divBudget; public: Budget ( void ) { divBudget = 0; } void addBudget ( double b ) { divBudget += b; corpBudget += b; } double getDivBudget ( void ) { return divBudget; } double getCorpBudget ( void ) { return corpBudget; } }; // Budget double Budget::corpBudget = 0; // Static member #endif

6 CS 1410 - SJAllan Chapter 14 6 testB udget.cpp – Program #include #include "Budget.h" using namespace std; int main ( void ) {int count; const int NUMDIVISIONS = 4; Budget divisions[NUMDIVISIONS]; for ( int count = 0; count < NUMDIVISIONS; count++ ) {double bud; cout << "Enter the budget request for division "; cout << (count + 1) << ": "; cin >> bud; divisions[count].addBudget(bud); } // for

7 CS 1410 - SJAllan Chapter 14 7 testB udget.cpp – Program cout << fixed << showpoint < setprecision(2); cout << "\nHere are the division budget requests:\n"; for ( int count = 0; count < NUMDIVISIONS; count++ ) {cout << "\tDivision " << (count + 1) << "\t$ "; cout << divisions[count].getDivBudget() << endl; } // for cout << "\tTotal Budget Requests:\t$ "; cout << divisions[0].getCorpBudget() << endl; return 0; } // main

8 CS 1410 - SJAllan Chapter 14 8 testBudget.cpp – Output Enter the budget request for Division 1: 100000 [Enter] Enter the budget request for Division 2: 200000 [Enter] Enter the budget request for Division 3: 300000 [Enter] Enter the budget request for Division 4: 400000 [Enter] Here are the division budget requests: Division 1$ 100000.00 Division 2$ 200000.00 Division 3$ 300000.00 Division 4$ 400000.00 Total Budget Requests:$ 1000000.00

9 CS 1410 - SJAllan Chapter 14 9 Static Member Functions Declared with static before return type: static int getVal ( ) { return valueCount; } Can only access static member data Can be called independent of objects: cout << "There are " << IntVal::getVal( ) << " objects\n " ;

10 CS 1410 - SJAllan Chapter 14 10 A New B udget.h – Program #ifndef BUDGET_H #define BUDGET_H class Budget {private: static double corpBudget; double divBudget; public: Budget ( void ) { divBudget = 0; } void addBudget ( double b ) { divBudget += b; corpBudget += b; } double getDivBudget ( void ) { return divBudget; } double getCorpBudget ( void ) { return corpBudget; } static void mainOffice ( double ); }; // Budget #endif

11 CS 1410 - SJAllan Chapter 14 11 Budget.cpp – Program #include "budget.h" double Budget::corpBudget = 0; void Budget::mainOffice ( double moffice ) {corpBudget += moffice; } // Budget::mainOffice

12 CS 1410 - SJAllan Chapter 14 12 testBudget.cpp – Program #include #include "Budget.h" using namespace std; int main ( void ) {int count; double mainOfficeRequest const int NUMDIVISIONS = 4; cout << "Enter the main office's budget request: "; cin >> mainOfficeRequest; Budget::mainOffice( mainOfficeRequest ); Budget divisions[NUMDIVISIONS]; for ( count = 0; count < NUMDIVISIONS; count++ ) {double budgetAmount; cout << "Enter the budget request for division "; cout << ( count + 1 ) << ": "; cin >> budgetAmount; divisions[count].addBudget( budgetAmount ); } // for

13 CS 1410 - SJAllan Chapter 14 13 testBudget.cpp – Program cout << fixed << showpoint << setprecision(2); cout << "\nHere are the division budget requests:\n"; for (int count = 0; count < NUMDIVISIONS; count++) {cout << "\tDivision " << ( count + 1 ) << "\t$ "; cout << divisions[count].getDivBudget() << endl; } // for cout << "\tTotal Budget Requests (including main office):\t$ "; cout << divisions[0].getCorpBudget( ) << endl; return 0; } // main

14 CS 1410 - SJAllan Chapter 14 14 testB udget.cpp – Output Enter the main office's budget request: 100000 [Enter] Enter the budget request for Division 1: 100000 [Enter] Enter the budget request for Division 2: 200000 [Enter] Enter the budget request for Division 3: 300000 [Enter] Enter the budget request for Division 4: 400000 [Enter] Here are the division budget requests: Division 1$ 100000.00 Division 2$ 200000.00 Division 3$ 300000.00 Division 3$ 400000.00 Total Requests (including main office): $ 1100000.00

15 CS 1410 - SJAllan Chapter 14 15 Friends of Classes Friend  A function or class that is not a member of a class, but has access to private members of the class A friend function can be a stand-alone function or a member function of another class It is declared a friend of a class with friend keyword in the function prototype

16 CS 1410 - SJAllan Chapter 14 16 Friend Function Declarations Stand-alone function: friend void setAVal ( intVal &, int );  Declares setAVal function be a friend of this class Member function of another class: friend void SomeClass::setNum( int num );  setNum function from Someclass class is a friend of this class

17 CS 1410 - SJAllan Chapter 14 17 Friend Classes As mentioned before, it is possible to make an entire class a friend of another class. class FriendClass { … }; // FriendClass class NewClass {public: friend class FriendClass; // declares entire class (Friendclass) as a friend of this class … }; // NewClass

18 CS 1410 - SJAllan Chapter 14 18 Memberwise Assignment The assignment operator (=) may be used to assign one object to another, or to initialize one object with another object’s data Thus v2 = v1; means that each member of one object is copied to its counterpart in the other object Use when class is defined: IntVal v3 = v2;

19 CS 1410 - SJAllan Chapter 14 19 Copy Constructors A copy constructor is a special constructor, called whenever a new object is created and initialized with another object’s data Assume the class PersonInfo has a member variable as follows: name char *. Consider the following declarations:  PersonInfo person1( "Maria Jones-Tucker", 25 );  PersonInfo person2 = person1;

20 CS 1410 - SJAllan Chapter 14 20 PersonInfo person1("Maria Jones-Tucker", 25); Maria Jones-Tucker Dynamically allocated memory name p ointer

21 CS 1410 - SJAllan Chapter 14 21 PersonInfo person2 = person1; Maria Jones-Tucker Both objects’ name members point to the same section of memory person1’s name pointer person2’s name pointer Dynamically allocated memory

22 CS 1410 - SJAllan Chapter 14 22 Programmer Defined Copy Constructor Allows us to solve the problem with pointers PersonInfo::PersonInfo( PersonInfo &obj ) {name = new char[strlen( obj.name ) + 1]; strcpy( name, obj.name ); age = obj.age; } // PersonInfo::PersonInfo Copy constructor takes a reference parameter to an object of the class

23 CS 1410 - SJAllan Chapter 14 23 Programmer Defined Copy Constructor Consider the following: PersonInfo info1( " Ann ", 5 ); PersonInfo info2 = info1; info2.setName( " Jane " ); name info1 name info2 “Ann”“Jane”

24 CS 1410 - SJAllan Chapter 14 24 Using const Parameters Because copy constructors are required to use reference parameters, they have access to their argument’s data PersonInfo::PersonInfo( PersonInfo &obj ) They should not be allowed to change the parameters, therefore, it is a good idea to make the parameter const so it can’t be modified PersonInfo::PersonInfo( const PersonInfo &obj )

25 CS 1410 - SJAllan Chapter 14 25 The Default Copy Constructor If a class doesn’t have a copy constructor, C++ automatically creates a default copy constructor The default copy constructor performs a memberwise assignment

26 CS 1410 - SJAllan Chapter 14 26 Operator Overloading C++ allows you to redefine how standard operators work when used with class objects

27 CS 1410 - SJAllan Chapter 14 27 Overloading the = Operator This is done with a member function such as: void operator = ( const PersonInfo &right ); This member function is called as follows:  person2 = person1;  person2.operator = ( person1 );  Note that the parameter, right, is declared as a reference, for efficiency purposes The reference prevents the compiler form making a copy of the object being passed into the function Also note that the parameter is declared constant so the function does not accidentally change the contents of the argument

28 CS 1410 - SJAllan Chapter 14 28 Operator Overload – Program #include using namespace std; class PersonInfo {private: char *name; int age; public: PersonInfo ( char *n, int a ) { name = new char[strlen(n) + 1]; strcpy(name, n); age = a; } PersonInfo ( const PersonInfo &obj ) // Copy constructor { name = new char[strlen(obj.name) + 1]; strcpy(name, obj.name); age = obj.age; } ~PersonInfo ( void ) { delete [] name; } char *getName ( void ) { return name; } int getAge ( void ) { return age; } void operator= ( const PersonInfo &right ) { delete [] name; name = new char[strlen( right.name ) + 1]; strcpy(name, right.name); age = right.age; } }; // PersonInfo

29 CS 1410 - SJAllan Chapter 14 29 Operator Overload – Program int main ( void ) {PersonInfo jim("Jim Young", 27), bob("Bob Faraday", 32), clone = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; cout << "Now the clone will change to Bob and "; cout << "Bob will change to Jim.\n"; clone = bob; bob = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; return 0; } // main

30 CS 1410 - SJAllan Chapter 14 30 Operator Overload – Output The Jim Object contains: Jim Young, 27 The Bob Object contains: Bob Faraday, 32 The Clone Object contains: Jim Young, 27 Now the clone will change to Bob and Bob will change to Jim. The Jim Object contains: Jim Young, 27 The Bob Object contains: Jim Young, 27 The Clone Object contains: Bob Faraday, 32

31 CS 1410 - SJAllan Chapter 14 31 The = Operator’s Return Value If the operator= function returns a void, as in the previous example, then multiple assignment statements won’t work To enable a statement such as person3 = person2 = person1; you must have the following prototype: PersonInfo operator= (const PersonInfo &Right);

32 CS 1410 - SJAllan Chapter 14 32 The this Pointer this is a special built-in pointer that is available in any member function this contains the address of the object that called the member function The this pointer is passed as a hidden argument to all non-static member functions

33 Use of this pointer This refers to the class itself. CS 1410 - SJAllan Chapter 14 33

34 You can use “this” to refer to class variables. Class MyInt { private: int a; public: void MyInt(int a) { // The 'this' pointer is used to get access to class variable “a” rather than local variable “a” this->a = a; } void doit(){ } }; CS 1410 - SJAllan Chapter 14 34

35 You can use “this” even when it is the not required Class MyInt { private: int a; public: void MyInt(int a) { this->a = a; doit(); // both of these calls to the same thing. “this” is understood this->doit(); // both of these calls to the same thing. “this” is understood } void doit(){ cout << “just Called contructor”;} } }; CS 1410 - SJAllan Chapter 14 35

36 Sometimes you need a name for yourself. “this” is that name Class MyInt { private: int a; public: void MyInt(int a) { this->a = a; } MyInt* returnBigger(MyInt * other){ if (other->a > a) return other; return this; // If I am the bigger, return me! } }; CS 1410 - SJAllan Chapter 14 36

37 The this Pointer PersonInfo person1, person2; cout << person1.getName( ) << endl;  What does the this pointer point to? cout << person2.getName( ) << endl;  What does the this pointer point to? CS 1410 - SJAllan Chapter 14 37

38 CS 1410 - SJAllan Chapter 14 38 Using this – Program #include using namespace std; class PersonInfo {private: char *name; int age; public: PersonInfo ( char *n, int a ) { name = new char[strlen( n )+ 1]; strcpy( name, n ); age = a; }

39 CS 1410 - SJAllan Chapter 14 39 Using this – Program PersonInfo ( const PersonInfo &obj ) // Copy constructor { name = new char[strlen(obj.name)+ 1]; strcpy(name, obj.name); age = obj.age; } ~PersonInfo ( void ) { delete [] name; } char *getName ( void ) { return name; } int getAge ( void ) { return age; } const PersonInfo operator= ( const PersonInfo &right ) { delete [] name; name = new char[strlen( right.name ) + 1]; strcpy( name, right.name ); age = right.age; return *this; } }; // PersonInfo

40 CS 1410 - SJAllan Chapter 14 40 Using this – Program int main ( void ) {PersonInfo jim("Jim Young", 27), bob("Bob Faraday", 32), clone = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; cout << "Now the clone and Bob will change to Jim.\n"; clone = bob = jim; cout << "The Jim Object contains: " << jim.getName(); cout << ", " << jim.getAge() << endl; cout << "The Bob Object contains: " << bob.getName(); cout << ", " << bob.getAge() << endl; cout << "The Clone Object contains: " << clone.getName(); cout << ", " << clone.getAge() << endl; return 0; } // main

41 CS 1410 - SJAllan Chapter 14 41 Using this – Output The Jim Object contains: Jim Young, 27 The Bob Object contains: Bob Faraday, 32 The Clone Object contains: Jim Young, 27 Now the clone and Bob will change to Jim. The Jim Object contains: Jim Young, 27 The Bob Object contains: Jim Young, 27 The Clone Object contains: Jim Young, 27

42 CS 1410 - SJAllan Chapter 14 42 Issues of Operator Overloading You can change an operator’s entire meaning when you overload it – don’t You cannot change the number of operands taken by an operator  For example, the = symbol must always be a binary operator  Likewise, ++ and -- must always be unary operators The following operators cannot overloaded  ?:..* :: sizeof

43 CS 1410 - SJAllan Chapter 14 43 Operators That can be Overloaded

44 CS 1410 - SJAllan Chapter 14 44 feetinch.h – Program #ifndef FEETINCHES_H #define FEETINCHES_H class FeetInches {private: int feet; int inches; void simplify(void); public: FeetInches( int f = 0, int i = 0 ) { feet = f; inches = i; simplify(); } void setFeet( int f ) { feet = f; }

45 CS 1410 - SJAllan Chapter 14 45 feetinch.h – Program void setInches( int i ) { inches = i; simplify(); } int getFeet(void) { return feet; } int getInches(void) { return inches; } FeetInches operator + (const FeetInches &); FeetInches operator - (const FeetInches &); FeetInches operator ++ ( void ); // Prefix ++ FeetInches operator ++ ( int ); // Postfix ++ bool operator > ( const FeetInches & ); bool operator < ( const FeetInches & ); bool operator == ( const FeetInches & ); friend ostream &operator << ( ostream &, const FeetInches & ); friend istream &operator >> ( istream &, const FeetInches & ); };// FeetInches #endif

46 FeetInches Why didn’t we overload the assignment ( = ) operator? CS 1410 - SJAllan Chapter 14 46

47 simplify 3 feet 14 inches  4 feet 2 inches 5 feet -2 inches  4 feet 10 inches CS 1410 - SJAllan Chapter 14 47

48 CS 1410 - SJAllan Chapter 14 48 feetinc.cpp – Program #include #include "feetinch.h" void FeetInches::simplify ( void ) {if ( inches >= 12 ) {feet += (inches / 12); inches %= 12; } // if else if ( inches < 0 ) {feet -= ( ( abs( inches ) / 12 ) + 1 ); inches = 12 - ( abs( inches ) % 12 ); } // else } // FeetInches::simplify

49 CS 1410 - SJAllan Chapter 14 49 feetinc.cpp – Program FeetInches FeetInches::operator + ( const FeetInches &right ) { FeetInches temp; temp.inches = inches + right.inches; temp.feet = feet + right.feet; temp.simplify(); return temp; } // FeetInches::operator + FeetInches FeetInches::operator - ( const FeetInches &right ) {FeetInches temp; temp.inches = inches - right.inches; temp.feet = feet - right.feet; temp.simplify(); return temp; } // FeetInches::operator -

50 CS 1410 - SJAllan Chapter 14 50 feetmain.cpp – Program #include #include "feetinc2.h“ using namespace std; int main ( void ) {FeetInches first, second, third; int f, i; cout << "Enter a distance in feet and inches: "; cin >> f >> i; first.setData(f, i); cout << "Enter another distance in feet and inches: "; cin >> f >> i; second.setData(f, i); third = first + second; cout << "First + Second = "; cout << third.getFeet() << " feet, "; cout << third.getInches() << " inches.\n"; third = first - second; cout << "First - Second = "; cout << third.getFeet() << " feet, "; cout << third.getInches() << " inches.\n"; return 0; } // main

51 CS 1410 - SJAllan Chapter 14 51 feetmain.cpp – Output Enter a distance in feet and inches: 6 5 [Enter] Enter another distance in feet and inches: 3 10 [Enter] First + Second = 10 feet, 3 inches. First - Second = 2 feet, 7 inches.

52 CS 1410 - SJAllan Chapter 14 52 Note: No return type is specified in the function header for the previous example  Because it is a FeetInches -to- double conversion function, it will always return a double

53 CS 1410 - SJAllan Chapter 14 53 Overloading the Prefix ++ Operator FeetInches FeetInches::operator ++ ( void ) { ++inches; simplify(); return *this; } // FeetInches::operator ++

54 What is Output? int num 4; cout << num++; int num = 4; Cout << ++num; CS 1410 - SJAllan Chapter 14 54 4 5

55 CS 1410 - SJAllan Chapter 14 55 Overloading the Postfix ++ Operator FeetInches FeetInches::operator ++ ( int ) { FeetInches temp( feet, inches ); inches++; simplify(); return temp; } // FeetInches::operator++

56 CS 1410 - SJAllan Chapter 14 56 Overloading Relational Operators if (distance1 < distance2) { … code … } // if

57 CS 1410 - SJAllan Chapter 14 57 Overloading Relational Operators bool FeetInches:: operator > ( const FeetInches &right ) { if (feet > right.feet) return true; else if (feet == right.feet && inches > right.inches) return true; else return false; } // FeetInches::operator >

58 CS 1410 - SJAllan Chapter 14 58 Overloading the == Operator bool FeetInches::operator == ( const FeetInches &right ) { if ( feet == right.feet && inches == right.inches ) return true; else return false; } // FeetInches::operator ==

59 CS 1410 - SJAllan Chapter 14 59 Overloading the << Operator ostream &operator << ( ostream &strm, FeetInches &obj ) { strm << obj.feet << " feet, " << obj.inches << " inches"; return strm; } // operator <<

60 CS 1410 - SJAllan Chapter 14 60 Overloading the >> Operator istream &operator >> ( istream &strm, FeetInches &obj ) { cout << "Feet: "; strm >> obj.feet; cout << "Inches: "; strm >> obj.inches; return strm; } // operator >>

61 CS 1410 - SJAllan Chapter 14 61 Overloading the [ ] Operator In addition to the traditional operators, C++ allows you to change the way the [ ] (subscript) symbols work Must consider constructor, destructor Overloaded [ ] returns a reference to the object, and not the object itself

62 CS 1410 - SJAllan Chapter 14 62 Intarry.h – Program #ifndef INTARRY_H #define INTARRY_H class IntArray { private: int *aptr; int arraySize; void subscriptError( ); public: IntArray ( int ); // constructor IntArray ( const IntArray & ); //copy constructor ~IntArray ( void ); // Destructor int size ( void ) { return arraySize }; int &operator [] ( const int & ); // overloaded [ ] operator }; // IntArray #endif

63 CS 1410 - SJAllan Chapter 14 63 Intarray.cpp – Program IntArray::IntArray ( int s ) { arraySize = s; aptr = new int [s]; for ( int count = 0; count < arraySize; count++ ) *( aptr + count ) = 0; } // IntArray::IntArray IntArray::IntArray ( const IntArray &obj ) { arraySize = obj.arraySize; aptr = new int [arraySize]; assert( aptr ); for ( int count = 0; count < arraySize; count ++ ) *( aptr + count ) = *( obj.aptr + count ); } // IntArray::IntArray

64 CS 1410 - SJAllan Chapter 14 64 Intarray.cpp – Program IntArray::~IntArray ( void ) { if ( arraySize > 0 ) delete [] aptr; } // IntArray::~IntArray int &IntArray::operator [] ( const int &sub ) { if ( sub arraySize ) subscriptError(); return aptr[sub]; } // IntArray::operator []

65 CS 1410 - SJAllan Chapter 14 65 Intarray.cpp – Program void IntArray::subscriptError( void ) {cout << "ERROR: Subscript out of range.\n"; exit( 0 ); } // IntArray::subscriptError

66 CS 1410 - SJAllan Chapter 14 66 Object Conversion Special operator functions may be written to convert a class object to any other type FeetInches::operator double ( void ) { double temp = feet; temp += ( inches / 12.0 ); return temp; } // FeetInches::operator double

67 CS 1410 - SJAllan Chapter 14 67 Creating a String Class This example shows the use of a C++ class to create a string data type

68 CS 1410 - SJAllan Chapter 14 68 The MyString Class Memory is dynamically allocated for any string stored in a MyString object Strings may be assigned to a MyString object with the = operator One string may be concatenated to another with the += operator Strings may be tested for equality with the == operator

69 CS 1410 - SJAllan Chapter 14 69 MyString.h – Program #ifndef MYSTRING_H #define MYSTRING_H #include using namespace std; class MyString; // Forward declarations ostream &operator << ( ostream &, const MyString & ); istream &operator >> ( istream &, MyString & ); class MyString {private: char *str; int len; public: MyString( void ) { str = NULL; len = 0; } MyString( char * ) {len = strlen( sptr ); str = new char[len + 1 ]; strcpy( str, sptr; }

70 CS 1410 - SJAllan Chapter 14 70 MyString.h – Program MyString( MyString &right) // Copy constructor {str = new char[ right.length() + 1]; strcpy( str, right.getValue() ); len = right.length(); } ~MyString( void ) { if ( len != 0 ) delete [] str; } int length ( void ) { return len; } char *getValue ( void ) { return str; };

71 CS 1410 - SJAllan Chapter 14 71 MyString.h – Program // Overloaded operators MyString operator += ( MyString & ); char *operator += ( const char * ); MyString operator = ( MyString & ); char *operator = ( const char * ); int operator == ( MyString & ); int operator == ( const char * ); int operator != ( MyString & ); int operator != ( const char * ); bool operator > ( MyString & ); bool operator > ( const char * ); bool operator < ( const char * ); bool operator < ( MyString & ); bool operator >= ( MyString & ); bool operator >= ( const char * ); bool operator <= ( const char * ); bool operator <= ( MyString & ); friend ostream &operator << ( ostream &, MyString & ); friend istream &operator >> ( istream &, MyString & ); }; // MyString #endif

72 CS 1410 - SJAllan Chapter 14 72 MyString.cpp – Program #include #include "MyString.h" using namespace std; MyString MyString::operator = ( MyString &right ) { if ( len != 0 ) delete []; str = new char[right.length() + 1]; strcpy(str, right.getValue()); len = right.length(); return *this; } // MyString::operator = MyString MyString::operator = ( const char *right ) {if ( len != 0 ) delete [] str; len = strlen( right ); str = new char[len + 1]; strcpy( str, right ); return *this; } // MyString::operator =

73 CS 1410 - SJAllan Chapter 14 73 MyString.cpp – Program MyString MyString::operator += ( MyString &right ) {char *temp = str; str = new char[strlen(str) + right.length() + 1]; strcpy( str, temp ); strcat( str, right.getvalue() ); if ( len != 0 ) delete [] temp; len = strlen(str); return *this; } // MyString::operator +=

74 CS 1410 - SJAllan Chapter 14 74 MyString.cpp – Program (cont) char *MyString::operator += ( const char *right ) {char *temp = str; str = new char[strlen(str) + strlen(right) + 1]; strcpy( str, temp ); strcat( str, right ); if ( len != 0 ) delete [] temp; return str; } // MyString::operator += int MyString::operator == ( MyString &right ) {return !strcmp( str, right.getValue() ) ; } // MyString::operator ==

75 CS 1410 - SJAllan Chapter 14 75 MyString.cpp – Program int MyString::operator == ( const char *right ) {return !strcmp( str, right ); } // MyString::operator == int MyString::operator != ( MyString &right ) {return strcmp( str, right.getValue() ); } // MyString::operator != int MyString::operator != ( const char *right ) {return strcmp( str, right ); } // MyString::operator != bool MyString::operator >(MyString &right) {if ( strcmp( str, right.getValue() ) > 0 ) return true; else return false; } // MyString::operator >

76 CS 1410 - SJAllan Chapter 14 76 MyString.cpp – Program bool MyString::operator > ( const char *right ) {if ( strcmp( str, right ) > 0 ) return true; else return false; } // MyString::operator > bool MyString::operator < ( MyString &right ) {if ( strcmp( str, right.getValue() ) < 0 ) return true; else return false; } // MyString::operator < bool MyString::operator < ( const char *right ) {if ( strcmp( str, right ) < 0 ) return true; else return false; } // MyString::operator <

77 CS 1410 - SJAllan Chapter 14 77 MyString.cpp – Program bool MyString::operator >= ( MyString &right ) {if ( strcmp( str, right.getValue() ) >= 0 ) return true; else return false; } // MyString::operator >= bool MyString::operator >= ( const char *right ) {if ( strcmp( str, right ) >= 0 ) return true; else return false; } // MyString::operator >= bool MyString::operator <= ( MyString &right ) {if ( strcmp( str, right.getValue() ) <= 0 ) return true; else return fals; } // MyString::operator <=

78 CS 1410 - SJAllan Chapter 14 78 MyString.cpp – Program bool MyString::operator <= (const char *right ) {if ( strcmp( str, right ) <= 0 ) return true; else return false; } // MyString::operator <= ostream &operator << ( ostream &strm, const MyString &obj ) {strm << obj.str; return strm; } // operator << istream &operator >>( istream &strm, MyString &obj ) {strm.getline(obj.str, obj.len); strm.ignore(); return strm; } // operator >>

79 CS 1410 - SJAllan Chapter 14 79 MystrMain.cpp – Program #include #include "Mystring.h" using namespace std; int main ( void ) {MyString object1("This"), object2("is"); MyString object3("a test."); MyString object4 = object1; MyString object5("is only a test."); char string1[] = "a test."; cout << "Object1: " << object1 << endl; cout << "Object2: " << object2 << endl; cout << "Object3: " << object3 << endl; cout << "Object4: " << object4 << endl; cout << "Object5: " << object5 << endl;

80 CS 1410 - SJAllan Chapter 14 80 MystrMain.cpp – Program cout << "String1: " << string1 << endl; object1 += " "; object1 += object2; object1 += " "; object1 += object3; object1 += " "; object1 += object4; object1 += " "; object1 += object5; cout << "Object1: " << object1 << endl; return 0; } // main

81 CS 1410 - SJAllan Chapter 14 81 MystrMain.cpp – Output Object1: This Object2: is Object3: a test. Object4: This Object5: is only a test. String1: a test. Object1: This is a test. This is only a test.

82 CS 1410 - SJAllan Chapter 14 82 MystrMain.cpp – Program #include #include “Mystring.h“ using namespace std; int main ( void ) {MyString name1("Billy"), name2("Sue"); MyString name3("joe"); MyString string1("ABC"), string2("DEF"); cout << “name1: " << name1.getValue() << endl; cout << “name2: " << name2.getValue() << endl; cout << “name3: " << name3.getValue() << endl; cout << “string1: " << string1.getValue() << endl; cout << “string2: " << string2.getValue() << endl;

83 CS 1410 - SJAllan Chapter 14 83 MystrMain.cpp – Program if ( name1 == name2 ) cout << “name1 is equal to Name2.\n"; else cout << “name1 is not equal to Name2.\n"; if ( name3 == "joe" ) cout << “name3 is equal to joe.\n"; else cout << “name3 is not equal to joe.\n"; if ( string1 > string2 ) cout << “string1 is greater than String2.\n"; else cout << “string1 is not greater than String2.\n"; if ( string1 < string2 ) cout << “string1 is less than String2.\n"; else

84 CS 1410 - SJAllan Chapter 14 84 MystrMain.cpp – Program cout << "string1 is not less than String2.\n"; if ( string1 >= string2 ) cout << "string1 is greater than or equal to " << "string2.\n"; else cout << "string1 is not greater than or equal to " << "string2.\n"; if ( string1 >= "ABC" ) cout << "string1 is greater than or equal to " << "ABC.\n"; else cout << "string1 is not greater than or equal to " << "ABC.\n"; if ( string1 <= string2 ) cout << "string1 is less than or equal to " << "string2.\n";

85 CS 1410 - SJAllan Chapter 14 85 MystrMain.cpp – Program else cout << "string1 is not less than or equal to " << "string2.\n"; if (string2 <= "DEF") cout << "string2 is less than or equal to " << "DEF.\n"; else cout << "string2 is not less than or equal to " << "DEF.\n"; return 0; } // main

86 CS 1410 - SJAllan Chapter 14 86 MystrMain.cpp – Output name1: Billy name2: Sue name3: joe string1: ABC string2: DEF name1 is not equal to Name2. name3 is equal to joe. string1 is not greater than String2. string1 is less than String2. string1 is not greater than or equal to String2. string1 is greater than or equal to ABC. string1 is less than or equal to String2. string2 is less than or equal to DEF.

87 CS 1410 - SJAllan Chapter 14 87 Object Composition Object composition occurs when a class contains an instance of another class Creates a “has a” relationship between classes The notation for structures within structures is used with object composition


Download ppt "Chapter 14 More About Classes. CS 1410 - SJAllan Chapter 14 2 Instance and Static Members Instance variable:  A member variable in a class  Each object."

Similar presentations


Ads by Google