8-OpOverload - Lecture 8 Meng Su 1 Today’s Topics Review...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 8. Meng Su 2/14/2011 1 Today’s Topics Review C++ string, struct, struct, Overloading Operators 1. 2. 2. 1. 2. 2. External way (not as a class member) Internal way (as a class member) 2/14/2011 2 Standard C++ String Class #include <string> #include Variety Variety of constructors provided for defining strings Define Define (instantiate) an empty string object string string s; Define Define a string initialized with another string string s("some other string”); // also convert C-string to C++ string CNote Note further options in text, page 216 Table 5-7 5String Constructors 2/14/2011 3 1 The C++ String Class Methods If If you have a string object s, you can: you Get Get the size of the string by using s.length() s.length() or s.size() or s.size() Check Check if string is empty by using: s.empty() () Note Note Table 5-8 in text page 217 5- 2/14/2011 4 More More string Member Functions Categories: Categories: assignment: assign, assignment: assign, copy, data modification: append, modification: append, clear, erase, erase, insert, replace, swap substrings: find, substr find, string string is a big class defined in the library. Read text sec5.2 and table D.4 page D7 to D14 for more string string members and examples online: http://cplusplus.com/reference/string/ 2/14/2011 5 I/0 for a string Object string Output: Output: use any ostream such as cout << s cout Input Input Can Can use >> operators >> Use getline Use getline function to put a line of input, including spaces, into a string: string address; cout << "Enter your address: "; getline(cin, getline(cin, address); Read text page 218-219 for the comparison!!! 218- 2/14/2011 6 2 string Overloading Operators OPERATOR MEANING >> input characters from stream up to whitespace, into string output string into stream << = assigns string on right to string object on left += appends string on right to end of contents on left + concatenates two strings references character in string using array notation >, >=, <, <=, ==, != relational operators for string comparison. Return true true or false false 2/14/2011 7 string Comparison Can Can use relational operators directly to compare string objects: string str1 = “Cmpsc410", “Cmpsc410", str2 = “Cse122"; if (str1 < str2) cout << str1 << " is less than " << str2; Comparison Comparison is performed similar to strcmp function. Result is true or false true false 2/14/2011 8 string Operators Example string word1, phrase; string word2 = "Dog"; cin >> word1; // user enters "Hot Tamale" // word1 has "Hot" phrase = word1 + word2; // phrase has // // "Hot Dog" phrase += " on a bun"; for (int i = 0; i < 16; i++) (int cout << phrase[i]; // displays phrase[i // "Hot Dog on a bun" 2/14/2011 9 3 Converters Between C++ String and C-String CFrom CFrom C-string (char array) -> to C++ string: to use the constructor: char cs[80] = “cmpsc 122” cs[80] “cmpsc string s(cs); s(cs); cout << s; // print: cmpsc 122 From From C++ string -> to C-string (char array) : to Cuse the string methods: c_str() or data() c_str() data() char * cs; cs; string s, filename; …… cs = s.c_str();// or use s.data() s.c_str();// s.data() // especially used in ifstream iso(filename.data()); // or iso(filename.data()); ifstream iso; iso; iso.open(filename.c_str()); iso.open(filename.c_str()); 2/14/2011 10 Recall: Common used functions in <cstring> <cstring> strlen(char strlen(char * s): strlen returns the length of its string argument. Does not count the null ’’\0’ at the end Does \ strcpy(char* dest, strcpy(char* dest, char* source) : Copies characters from source to dest. Copies up to, and including the first ’\0’ dest. ’\ strcmp(char* strcmp(char* s1, char* s2) : Compares s1 to s2 and returns an int int describing the comparison (<0,==0,>0 means: s1 <,==,> s2 ) s1 <, s2 strcat(char* dest, strcat(char* dest, char* source):Appends characters from source to dest. dest. operators operators >> and <<: can be used for input and output <<: can All the parameters are C-string names (char array with ‘‘\0’) C\ See text page 214 and Appendix D.2 for more 2/14/2011 11 Comparing C-string and C++-string CC++C-string is an array of chars with null character at the end of the array. has has about twenty functions defined in the library <cstring> cstring> C++C++-string is a class object. has has near a hundred methods in the library <string> <string> can can use many operators such as +, +=, <, <=,… C++ C++ string is safer and arguably easier than using C-strings CWe’ll We’ll practice standard C++ string in our new assignments. 2/14/2011 12 4 Structures Characteristics Characteristics of traditional struct from C Elements Elements may be of different type and size, but are ordered. Example Example of declaring a struct type: struct Date { int month, day, year; day year; char dayOfWeek[12]; dayOfWeek[12]; }; Define Define a variable (an instance) of the type Date Date today; Date holidays[10]; // // an array of Date objects Date 2/14/2011 13 Structures Access Access members with name name of struct object dot (member selector operator) . dot name name of struct member Date today = { 3, 4, 2005, "Tuesday“}; cout << today.month; month; 2/14/2011 14 The only difference in the C++ struct ClassName { public: //default can be dropped here Declarations of public members private: }; Declarations of private members class ClassName { private: //default can be dropped here Declarations of private members public: Declarations of public members }; 2/14/2011 15 5 5. Modularity Problem: Redundant Declarations Suppose Suppose a prog needs the Time class, so it #include "Time.h" "Time.h" The The prog also needs another class Book, so it also Book, #include “Book.h" “Book.h" But class Book use class Time, so Book.h But so Book #include “Time.h" “Time.h" What’s What’s happened? Time.h is included twice in prog! prog! causes "redeclaration errors " at compile time. "redeclaration How How to solve this problem? 2/14/2011 16 Solution: Solution: Conditional Compilation Use Use conditional compilation: put the following compiler directives in *.h file : Example Example (text Fig 4.10 page 182 for Time.h): #ifndef TIME // put at the beginning of the header file, #define TIME // any name is ok, but using class name in capital letter is popular …… // class declaration and other codes #endif //at the end of this file You You should use it (with different names in different header files if there are many) in your assignment ! 2/14/2011 17 Review: Time Class class Time { public: public: Time (); Time(unsigned hours, unsigned minutes, char ampm); hours, minutes, ampm); void Set(unsigned hours unsigned minutes char ampm void Set(unsigned hours, unsigned minutes, char ampm); void Display(ostream & out); Display(ostream private: }; unsigned hours, minutes; minutes; char ampm; ampm; unsigned myMilTime; myMilTime; 2/14/2011 18 6 2. Overloading Operators Same Same operator symbol can be used more than one way Examples: Examples: + not only for integers, but also for integers, doubles, doubles, for strings,…… strings,…… Programmer Programmer can redefine the meaning of these operator symbols like +, -, ... for using in our own ... classes such as Time,… Two Two methods of overloading an operator: By By defining as an external functions which is not a member of the class. By By defining as an internal member function of the class. 2/14/2011 19 Examples of Operator Overloading (External) Note Note the overloaded I/O operators << and >> in the expanded Time class >> Fig 4.7 on page 172-176 on 172Δ Note Note these operators overloading are defined as defined external external functions (internal method later). later). 2/14/2011 20 In In .h file: declare it, (outside of the class) ostream & operator<<(ostream & out, operator<<(ostream const Time & t); In .cpp In .cpp file: define it, ostream & operator<<(ostream & out, operator<<(ostream const Time & t) { t.display(out); return out; } t.display(out); In In main.cpp file: use it, Time bedTime; bedTime; …… cout << bedTime; bedTime; // if display is public, it is same as bedTime.display(cout); bedTime.display(cout); 2/14/2011 21 7 Similar Similar for >> and other operators, one more example: overload “great than” > for Time In In .h file: declare it, bool operator>(const Time & t1, operator>(const const Time & t2); In .cpp In .cpp file: define it, bool operator>(const Time &t1, operator>(const const Time &t2) {return t1.getMilTime() > t2.getMilTime();} In In main.cpp file: use it, Time mealTime, classTime; mealTime, classTime; …… if (classTime > mealTime) (classTime mealTime) { ……… } 2/14/2011 22 Syntax of Operator Overloading (external) Suppose Suppose the operator is ∆ ReturnType operator∆( type1 x, type2 y) { …… } After After the definition we can use a∆b is equivalent to call operator∆( a, b) However, However, some operators like ::, ., etc. can not ::, can be overloaded. 2/14/2011 23 Similar Similar for >> and other operators, one more example: overload “great than” > for Time In In .h file: declare it, bool operator>(const Time & t1, operator>(const const Time & t2); In .cpp In .cpp file: define it, bool operator>(const Time &t1, operator>(const const Time &t2) {return t1.getMilTime() > t2.getMilTime();} In In main.cpp file: use it, Time mealTime, classTime; mealTime, classTime; …… if (classTime > mealTime) (classTime mealTime) { ……… } 2/14/2011 24 8 Internal Method: Syntax (compare with external way) Suppose Suppose the binary operator is ∆ In In .h file: declare it (inside of class) class) class className {… ReturnType operator∆(type y); … } In .cpp file: define it, In ReturnType ClassName::operator∆(type y) ::operator { …… } In In main.cpp file: use it, used same as defined in external way: a∆b is equivalent to call a. operator∆(b) 2/14/2011 25 Example: Overloading Operator < as a member function (internal) In In .h file: declare it in the class Time, class class Time{ public:…… bool operator<(const Time & t); operator<(const …… } In In .cpp file: define it, bool Time::operator<(const Time & t) Time:: (const Time t) { return myMilTime < t.getMilTime(); } In In main.cpp file: use it (same as in the first way ) , Time mealTime, classTime; …… if (classTime < mealTime) (classTime mealTime) { ……… } 2/14/2011 26 Which operators can be overloaded? You can overload any of the following operators (not complete): + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> <<= >>= == != <= >= && || ++ -- , -> () You cannot overload the following operators (not complete): . :: ?: You cannot overload the symbol # 2/14/2011 27 9 For output <<, input >> operators << >> However, However, we can NOT use the internal way, (i.e. define as class members) to overload I/O operators << and >> !! >> See See it again: ostream ostream & operator<<(ostream & out, Time & t) Ti t) const { t.display(out); t.display(out); return out; } Define a method display and call it in the definition and of the overloading 2/14/2011 28 void Time::display(ostream & out) const Time::display(ostream { out << myHours << ':' << (myMinutes < 10 ? "0" : "") << myMinutes << ' ' << myAMorPM << ".M. (" << myMilTime << " mil. time)"; } “Overloading <<“ let user can use cout cout << classTime; instead of classTime.display(cout); classTime.display(cout); for output Similar way for overloading input operator >> (text Fig 4.7 ) Question: Question: Can we put the statements in display method inside of the overloading << function directly? ostream & operator<<(ostream & out, const Time & t) { …… } 2/14/2011 29 Reference Some Some slides are adapted from slides of text: ADTs, Data Structures and Problem Solving with C++, Second Edition by Nyhoff Text website: http://cs.calvin.edu/books/c++/ds/2e/ Clip Clip images are selected from WebPages of Microsoft Clip Art and Media 2/14/2011 30 10 ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online