1 / 111

Review: C Introduction to C with OOP

?????????? ???. 2. Agenda. From C to C (C == a better C Objec-Oriented support) a. I/O stream, b. pass-by-reference c. function name overloading, d.operator overloading, e. default parameter, f.inline function, g.template functionData Abstraction: Why using struct? Why using class?

zelia
Download Presentation

Review: C Introduction to C with OOP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. ?????????? ??? 1 Review: C++???????? Introduction to C++ with OOP ??? tsaiwn@csie.nctu.edu.tw tsaiwn@cs.nctu.edu.tw ??????????

    2. ?????????? ??? 2 Agenda From C to C++ (C++ == a better C + Objec-Oriented support) a. I/O stream, b. pass-by-reference c. function name overloading, d.operator overloading, e. default parameter, f.inline function, g.template function Data Abstraction: Why using struct? Why using class? An ADT example: How to design/construct/use a Stack? Introduction to OOA, OOD, and UML Inheritance and examples: Animal and Mankind, Vector and Stack virtual function and Polymorphism: How it works? Generic programming: template function/class, and STL Exceptions: Scope of exceptions, raising exception, exception handlers More tips about class and ADT: a. constructor/Destructor, b. class members vs. instance members, c.friend and access control of class members

    3. ?????????? ??? 3

    4. ?????????? ??? 4 C++ Template (??) Templates provide direct support for generic programming The C++ template mechanism allows a type to be a parameter in the definition of a class or a function definer specifies the container class in terms of that argument users specify what the type of contained objects is The template implementation is a mechanism that generates types when needed based on the users specification (compiler ??copy??? ) Every major standard library abstraction is represented as a template

    5. ?????????? ??? 5 C++ Function Template (????) Compare sort definition to the sort( ) defined in chapter7.7. This templatized version is cleaner and shorter because it can rely on more information about the type of the elements it sorts It is faster because it doesnt rely on a pointer to function for the comparison. This implies that no indrect function calls are needed and that inlining of a simple is < is easy Compare sort definition to the sort( ) defined in chapter7.7. This templatized version is cleaner and shorter because it can rely on more information about the type of the elements it sorts It is faster because it doesnt rely on a pointer to function for the comparison. This implies that no indrect function calls are needed and that inlining of a simple is < is easy

    6. ?????????? ??? 6 template function template <class T> void swap( T & x, T & y) { T temp; temp=x; x = y; y = temp; }

    7. ?????????? ??? 7 C++ Class Template ?????????? data type???? A string is a class that holds characters and provides operations such as subscripting, concatenation and comparison We would like to provide that behavior for many different kinds of characters - string of signed characters - string of unsigned characters - string of Chinese characters - string of Greek charactersA string is a class that holds characters and provides operations such as subscripting, concatenation and comparison We would like to provide that behavior for many different kinds of characters - string of signed characters - string of unsigned characters - string of Chinese characters - string of Greek characters

    8. ?????????? ??? 8 Summary Template class To define Generic data type Allow the creation of reusable code Types are used as parameter in < > General form: template<class T, class T2> class class_name { // code here }; // do NOT forget ;

    9. ?????????? ??? 9 Genericity in Java Generic Java Prior to the JDK 1.5 (5.0) release, when you created a Collection, you could put any object in it. JDK 1.5 (5.0) and later versions provides compile-time type safety with the Java Collections framework through generics Generic Java extends Java with generic parameters for classes and methods: class Foo<T> Java generic idiom Use java.lang.Object as the most generic type Can specify constraints on type parameters class Foo<T implements Haha>

    10. ?????????? ??? 10 Standard Template Library (STL) Many template classes, functions Abstract Data Types Three general categories: Containers Iterators Algorithms Three kinds of containers: Sequences Associative Adapted

    11. ?????????? ??? 11 ?? C++ STL Library ? stack #include <stack> #include <iostream> using namespace std; /* where the Library in */ int main( ) { stack<int> xo; /* ???? stack<int> */ stack<double> brandy; /* ???? */ xo.push(880); xo.push(770); xo.push(53); while(! xo.empty( ) ){/* ?? empty ?? isempty */ cout << " " << xo.top( ); /* ??? top( ) */ xo.pop( ); /* pop is void type */ } cout << endl; /* new Line*/ return 0; }

    12. ?????????? ??? 12 first-class Containers in STL Sequences: vector: Dynamic-array-backed const-time random-access const-time insert/delete at back deque: double-ended queue fast random-access - how? fast insert/delete at front and back list: doubly-linked list fast insert/delete anywhere Associative: set: non-sequential, unique multiset: non-sequential, non-unique map: maps from keys to unique values multimap: maps to non-unique values

    13. ?????????? ??? 13 Container member ops & functions copy constructor empty( ) size( ) swap( ) First-class: begin( ) end( ) rbegin( ) rend( ) erase( ) clear( )

    14. ?????????? ??? 14 STL iterators Standard way to traverse through container: iteration Abstraction of both index and pointer just: means of iterating forward, back, etc. Iterator direction types: Forward iterator Reverse iterator both supported by vector, list, etc. Random-access iterator supported by vector Can be const or not

    15. ?????????? ??? 15 Types of iterators I/O iterators are one-pass can only move in one direction can only traverse once p++ Other types: bidirectional: p++, p-- random-access: p + i, p - i, p[i] *(p+i), p1 < p2 vector: random-access deque: random-access list: bidirectional set/multiset: bidirectional map/multimap: bidirectional

    16. ?????????? ??? 16 STL iterators iterio.cpp Access set of values from one place Usually, place is a container But: input stream may be construed as a place #include <iostream> #include <iterator> using namespace std; void main() { cout << Enter two nums: ; istream_iterator<int> intIn(cin); int x = *intIn; intIn++; x += *intIn; ostream_iterator<int> intOut(cout); cout << The sum is: ; *intOut = x; cout << endl; }

    17. ?????????? ??? 17 vector : ?????? array Most commonly used container class Fast random access random-access iterators Can access mems with []s like arrays unsafe with at(i) checks bounds, throws exception safer Essentially: dynamic array hidden in obj add to/delete from back: very fast, const time unless run out of space ? automatically copy to larger array insert/del from middle: linear time must move half of mems forward/back

    18. ?????????? ??? 18 vectors <vector> Similar to Javas Vector in that: dynamic-array-backed list same complexities Different in that: takes instance of specified type vector<int> nums; vector<double> vals(20); size-20 vector of doubles vector<Base> objs; takes Base objects vector<Base*> ptrs; takes Base*s

    19. ?????????? ??? 19 vector ???? #include <iostream> #include <vector> using namespace std; int main(){ vector<int> haha; //vector of integers //append elements 1 -> 6 for(int i=1; i<=6; ++i){ haha.push_back(i); } // print all elements followed by a space for(int i=0; i< haha.size(); ++i){ cout << haha[i] << << endl; } } //output = 1 2 3 4 5 6

    20. ?????????? ??? 20 STL deque Deque ????? de-k ; ?? dee-queue ???queue???? Term Deque is an abbreviation for Double Ended Queue A dynamic array implemented so it can grow in both dimensions. Inserting elements at beginning and the end is fast Inserting elements in the middle takes time since elements must be moved It is almost exactly the same as the vector example except that push_front() is used. Therefore order of elements is reversed on output. Could use push_back()member function also. push_front is not provided for vectors (Why?)

    21. ?????????? ??? 21 deque example #include <iostream> #include <deque> using namespace std; int main(){ deque<float> haha; //deque of floats //append elements 1 -> 6 for(int i=1; i<=6; ++i){ haha.push_front(i*1.1); } // print all elements followed by a space for(int i=0; i< haha.size(); ++i){ cout << haha[i] << " " << endl; } }

    22. ?????????? ??? 22 STL List Implemented as a doubly linked list of elements.

    23. ?????????? ??? 23 list example #include <iostream> #include <list> using namespace std; int main( ) { list<char> hehe; //list of characters //append elements 'a' -> 'z' for(char i= 'a'; i<= 'z' ; ++i) { hehe.push_front(i); } // print all elements followed by a space while(!hehe.empty( )){ cout << hehe.front( ) << " "; hehe.pop( ); } } // Output = a b c d e f g h I j k l m n o p q r s t u v w x y z

    24. ?????????? ??? 24 Other Containers in STL Container adapters: use first-class containers by composition stack: LIFO deque queue: FIFO deque Priority_queue --- queue sorted by value Near-containers: arrays string bitset valarray

    25. ?????????? ??? 25 C++ string #include<string> // ?? <string.h> using namespace std; string s1 = "James "; string s2 = " Bond "; string s3 = s1 + " " + s2; // concatenate ???? int main ( ) { // if (s1.substr(0,3) == "Jim ") { s1.replace(1,2, "ames ") } printf ( " the name is %s\n ", s1.c_str( ) ); //?? C ? string // . . .

    26. ?????????? ??? 26 STL Container Adapters In addition to the fundamental container classes, C++ provides special predefined container adapters that meet special needs. These are implemented on top of the fundamental container classes, and consist of: Stacks Manage elements with a Last in First Out (LIFO) policy. Queues First In First Out (FIFO) policy management. Act just like a normal buffer. Priority Queues Elements may have different priorities. Priority is based upon a sorting criterion. (default < is used). Act just like a buffer, where the next element out is always the element with the highest priority.

    27. ?????????? ??? 27 Iterators - Set Example #include <iostream> #include <set> int main( ) { typedef std::set<int> IntSet; IntSet hey; hey.insert(3); hey.insert(1); hey.insert(5); hey.insert(4); hey.insert(1); hey.insert(6); hey.insert(2); IntSet::const_iterator pos; for (pos=hey.begin(); pos!=hey.end(); ++pos){ std::cout << *pos << ' '; } }

    28. ?????????? ??? 28 Maps as associative arrays A collection of key/value pairs with unique keys (as guaranteed by map) can act just as an associative array. Consider: map<string, float> theData; theData[NULL] = 0; theData[PI] = 3.14157; theData[E] = -1.6E-19; map<string, float>::iterator pos; for(pos=theData.begin(); pos!=theData.end(); ++pos){ cout << key: [ << pos->first << ] << value: << pos->second << endl; }

    29. ?????????? ??? 29 Standard Algorithms (1/3) #include <algorithm> Needed in order to be able to call the algorithms Functions that read or modify a sequence: find(), count(), replace(), copy(), sort(), merge() Examples:

    30. ?????????? ??? 30 Standard Algorithms (2/3) Functions that apply a given function on each element of a sequence: foreach( ), find_if( ), count_if( ), replace_if( ) Example:

    31. ?????????? ??? 31 Standard Algorithms (3/3) Algorithms are not member functions of the containers. Implemented as global functions that operate with iterators. Thus implemented only once. +ve Reduces code size, +ve Increases flexibility Against OO principles - it is a generic functional programming paradigm. -ve Operation is not intuitive -ve Some container / algorithm combinations dont work -ve Worse still some may work but be hideously slow.

    32. ?????????? ??? 32 ????? ?? vector ? stack ? ?? list ? stack ? Inheritance == extends

    33. ?????????? ??? 33 ? vector ?? stack (1/2) [tsaiwn@ccbsd3] vectorSTK> cat -n mystk3.h 1 #include <vector> 2 using namespace std; 3 template <class T> 4 class MyStack { 5 vector <T> x; 6 public: 7 void push(T y) { 8 x.push_back(y); 9 } 10 T top( ) { 11 return x.back( ); 12 } 13 void pop( ) { 14 x.pop_back( ); 15 } 16 bool empty( ) { return x.begin() == x.end(); } 17 };

    34. ?????????? ??? 34 ? vector ?? stack (2/2) [tsaiwn@ccbsd3] vectorSTK> cat -n mymain3.cpp 1 // mymain3.cpp; g++ mymain3.cpp ; ./a.out 2 using namespace std; 3 #include "mystk3.h" 4 //????? 1999??? C++ ???, ???? <iostream.h> 5 #include<iostream> 6 int main( ) { 7 MyStack <int> x; // ???! 8 x.push(880); 9 x.push(770); 10 x.push(53); 11 while(!x.empty( ) ) { 12 cout << x.top(); x.pop(); 13 } 14 cout << endl; 15 } [tsaiwn@ccbsd3] vectorSTK> g++ mymain3.cpp [tsaiwn@ccbsd3] vectorSTK> ./a.out 53770880

    35. ?????????? ??? 35 ? list ?? stack (1/2) [tsaiwn@ccbsd3] vectorSTK> cat -n mystk5.h 1 #include <list> 2 using namespace std; 3 template <class T> 4 class MyStack { 5 list <T> x; 6 public: 7 void push(const T& y) { 8 x.push_front(y); 9 } 10 T top( ) { 11 return x.front( ); 12 } 13 void pop( ) { 14 x.pop_front( ); 15 } 16 bool empty( ) { return x.begin() == x.end(); } 17 };

    36. ?????????? ??? 36 ? list ?? stack (2/2) [tsaiwn@ccbsd3] vectorSTK> cat -n mymain5.cpp 1 // mymain5.cpp; g++ mymain5.cpp ; ./a.out 2 using namespace std; 3 #include "mystk5.h" 4 //????? 1999??? C++ ???, ???? <iostream.h> 5 #include<iostream> 6 int main( ){ 7 MyStack <int> x; // ???! 8 x.push(880); 9 x.push(770); 10 x.push(53); 11 while(!x.empty()){ 12 cout << x.top(); x.pop(); 13 } 14 cout << endl; 15 } [tsaiwn@ccbsd3] vectorSTK> g++ mymain5.cpp [tsaiwn@ccbsd3] vectorSTK> ./a.out 53770880

    37. ?????????? ??? 37 ? list ??? stack (1/2) [tsaiwn@ccbsd3] vectorSTK> cat -n mystk6.h 1 #include <list> 2 using namespace std; 3 template <class T> 4 class MyStack: list<T> { 5 public: 6 void push(const T& y) { 7 MyStack<T>::push_front(y); 8 } 9 T top( ) { 10 return MyStack<T>::front( ); 11 } 12 void pop( ) { 13 MyStack<T>::pop_front( ); 14 } 15 bool empty( ) { 16 return MyStack<T>::begin() == MyStack<T>::end( ); 17 } 18 }; // class

    38. ?????????? ??? 38 ? list ??? stack (2/2) [tsaiwn@ccbsd3] vectorSTK> cat -n mymain6.cpp 1 // mymain6.cpp; g++ mymain6.cpp ; ./a.out 2 using namespace std; 3 #include "mystk6.h" 4 //????? 1999??? C++ ???, ???? <iostream.h> 5 #include<iostream> 6 int main( ){ 7 MyStack <int> x; // ???! 8 x.push(880); 9 x.push(770); 10 x.push(53); 11 while(!x.empty()){ 12 cout << x.top(); x.pop(); 13 } 14 cout << endl; 15 } [tsaiwn@ccbsd3] vectorSTK> g++ mymain6.cpp [tsaiwn@ccbsd3] vectorSTK> ./a.out 53770880

    39. ?????????? ??? 39 Exceptions handling (1/2)

    40. ?????????? ??? 40 Exceptions handling (2/2) C++ introduces exception for error handling/exception handling. (to prevent bad behavior from getting worse) An exception is an event that is triggered by low level code to inform upper level code that an error condition has occurred. (an event is an Object) Exceptions require the use of three new C++ keywords: try catch throw Triggering an error condition is called throwing an exception. Handling the error is called catching the exception. try blocks are used to bound a set of statements that are to be monitored for all or a subset of exceptions which can be caught.

    41. ?????????? ??? 41 signal / setjmp / longjmp /** sig.c --- demo how to catch/handle the system signal ** by Wen-Nung Tsai. ** @CopyLeft reserved *** gcc sig.c *** a.out *******from "man signal": SYNOPSIS #include <signal.h> void (*signal(int sig, void(*func)(int))() *** In signal(), it will call func in this way: (*func)(sig); **********************/ extern long time(); /* in <sys/time.h> */ #include <signal.h> #include <setjmp.h> #include <stdio.h> void myisr1(int); /* an ISR to handle some interrupts */ void myisr2(int tni){printf("he he he!\n");}; /* for other signals */ long k=0, status=0, *p; jmp_buf env; /* for use in setjmp(), longjmp() */ // int main( )

    42. ?????????? ??? 42 sig.c (2/3) int main( ) { /*** tell the system we want to catch some signals ***/ signal(SIGINT, (void (*)(int)) myisr1 ); /* See K&R Appendix B9 */ signal(SIGSEGV, *myisr1 ); /* signal(SIGSEGV, (void (*)(int)) myisr1 ); */ printf("\nWelcome to Disney Land...\n"); srand(time(0)); /* use current time to set seed of rand() */ if(rand()%100 < 50){ if(setjmp(env)==0) /* See K&R Appendix B8 */ *p=38; /* ?????segmentation fault??? core dump ! */ else goto eoj; /* ???longjmp() ????? else ! */ } printf("Here we go!\n"); loop_a_while: while(k<12345){ printf("%ld ",k++); } printf("\n=== bye bye ===\n"); return 0; eoj: system("echo -n Now:"); system("date"); printf("\n=== abnormal stop:-(\n"); return 1; }

    43. ?????????? ??? 43 void myisr1(int x) /* Interrupt Service Routine */ { fflush(stdout); /* try to flush current buffer */ switch(x){ case SIGINT: printf("\nHey, [sig no=%d] Do NOT hit Control_C\n", x); k=12340; break; /* don't forget to take a break :-) */ default: printf("Outch! Seems Segmentation Falt or Fatal error\n"); status = 49; longjmp(env, 123); /* return a non-zero value */ } /*switch case*/ /* longjmp() will goto recent if(setjmp... */ return; }

    44. ?????????? ??? 44 ????????? exception handling ?? ?????? signal ???????????????????? ISR ??, ????? user?Control_C (SIGINT) ? segmentation falt???? ?? SIGSEGV falt??? *p=38 ??(because??allocate??? *p), ???????statement ???????(if(rand()%100<50)... ) ? ISR ?????????, ?? SIGSEGV??? Outch! Seems Segmentation Falt or Fatal error, ??? longjmp???????? setjmp ???, ??? setjmp()??? 0 (?longjump ????) ????eoj???????, (system call) ?? Control_C ???, ?? Hey, [sig no=2] Do NOT hit Control_C ?, ?????????(?? k == 12340), ????????? ????????, ???? 1 ?? 12344, ?????

    45. ?????????? ??? 45 These signals are defined in the file <signal.h> No Name Default Action Description 1 SIGHUP terminate process terminal line hangup 2 SIGINT terminate process interrupt program 3 SIGQUIT create core image quit program 4 SIGILL create core image illegal instruction 5 SIGTRAP create core image trace trap 6 SIGABRT create core image abort program (formerly SIGIOT) 7 SIGEMT create core image emulate instruction executed 8 SIGFPE create core image floating-point exception 9 SIGKILL terminate process kill program 10 SIGBUS create core image bus error 11 SIGSEGV create core image segmentation violation 12 SIGSYS create core image non-existent system call invoked 13 SIGPIPE terminate process write on a pipe with no reader 14 SIGALRM terminate process real-time timer expired 15 SIGTERM terminate process software termination signal 16 SIGURG discard signal urgent condition present on socket

    46. ?????????? ??? 46 <signal.h> (cont.) 17 SIGSTOP stop process stop (cannot be caught or ignored) 18 SIGTSTP stop process stop signal generated from keyboard 19 SIGCONT discard signal continue after stop 20 SIGCHLD discard signal child status has changed 21 SIGTTIN stop process background read attempted from control terminal 22 SIGTTOU stop process background write attempted to control terminal 23 SIGIO discard signal I/O is possible on a descriptor (see fcntl(2)) 24 SIGXCPU terminate process cpu time limit exceeded (see setrlimit(2)) 25 SIGXFSZ terminate process file size limit exceeded (see setrlimit(2)) 26 SIGVTALRM terminate process virtual time alarm (see setitimer(2)) 27 SIGPROF terminate process profiling timer alarm (see setitimer(2)) 28 SIGWINCH discard signal Window size change 29 SIGINFO discard signal status request from keyboard 30 SIGUSR1 terminate process User defined signal 1 31 SIGUSR2 terminate process User defined signal 2

    47. ?????????? ??? 47 Stack with Exception handling void Stack::push(const long item) throws BoundExp { if ( (sp+1) >= sizeof(data)/sizeof(data[0])) throw BoundExp(stack overflow); data[++sp] = item; //ok if here } //assume empty condition: sp == -1 What is BoundExp in this example? A class we defined (see next slide)

    48. ?????????? ??? 48 An exception class example class BoundExp: public exception { public: BoundExp(const string &s): exception( (const exception&)s ) { } // const char* what( ){ return "Bad news!"; } }; Its just a class Its parent is exception, but neednt be ! exception has function what() maybe other information

    49. ?????????? ??? 49 Throwing and catching exception Stack s; try { // s.push(38); // may cause exception } catch (BoundExp &ex) { cout << Error: << ex.what() << \n; } catch (Exception_Type2 &ex) { // can catch multiple kinds of exception // } catch () { //?????? is a wildcard! cout << Unknown exception caught.\n; }

    50. ?????????? ??? 50 Exception classes in C++ #include <exception> class exception #include <stdexcept> runtime_error, logic_error bad_alloc: when new failed bad_cast: when dynamic_cast failed Can throw non-exception objects And even primitives But handling easer if dont

    51. ?????????? ??? 51 The C++ stdexcept Hierarchy

    52. ?????????? ??? 52 Testing Standard exception #include <iostream> #include <stdexcept> using namespace std; int main( ) { int* ptr, i; try { for(i = 1; i<= 99999; ++i) ptr = new int[8888]; } catch ( bad_alloc ) { cerr << "i=" << i ; cerr <<" new: unable to allocate" << " storage...aborting\n"; exit( EXIT_FAILURE ); } delete ptr; return 0; }

    53. ?????????? ??? 53 Throwing Standard Exceptions (1/2) #include <iostream> #include <stdexcept> using namespace std; const int MAX_SIZE = 1000; float arr[ MAX_SIZE ]; float& access( int i ) { if( i < 0 ) throw out_of_range("index underflow"); if( i > MAX_SIZE ) throw out_of_range("index overflow"); return arr[i]; } int main() { for(int i=0; i<MAX_SIZE; i++) { arr[i] = i; }

    54. ?????????? ??? 54 Throwing Standard Exceptions (2/2) // after for loop initialization int k; cout <<"enter k"<< endl; cin >> k; float val; try { val = access( k ); cout <<"arr["<< k <<"] ="<< val << endl; } catch ( out_of_range ex ) { cerr << ex.what() << endl; exit( EXIT_FAILURE ); } return 0; }

    55. ?????????? ??? 55 /usr/include/g++/exception #ifndef __EXCEPTION__ #define __EXCEPTION__ #pragma interface "exception" extern "C++" { namespace std { // all STL libraries are in namespace std class exception { public: exception ( ) { } virtual ~exception ( ) { } virtual const char* what ( ) const; // you override it if necessary }; // . . . } // namespace std } // extern "C++" #endif

    56. ?????????? ??? 56 a simpler Exception example class Error{ }; // enough :-) void f( ) { // if(exception_condition) { throw Error(); } // }

    57. ?????????? ??? 57 Another exception example #include<iostream> using namespace std; template<class T> class Array { int capacity; T* pp; public: class ErrorRange{ }; Array(int cap=10) { pp = new T[cap]( ); capacity= 0; if(pp==0) { cout << "Array memory error.\n"; } capacity=cap; } T& operator[](int i) { if(i<0 || i >=capacity) throw ErrorRange(); return pp[i]; } };

    58. ?????????? ??? 58 Override what( ) in exception(1/2) Many exceptions provide a mechanism for obtaining more useful information in the form of a virtual method what(). This is present in the base class exception, and is overridden in derived classes to provide more info about the error. For example, try { connect(sony, 5); } catch(connection_error& e) { cout << "ERROR: [" << e.what() << "]" << endl; }

    59. ?????????? ??? 59 Override what( ) in exception(2/2) The exception class connection_error may looks like as follows: class connection_error : public std::exception { std::string msg; public: connection_error(std::string& msg) : msg(msg){ } virtual const char* what() const throw(){ return m_msg.c_str(); } }

    60. ?????????? ??? 60 More tips about class and ADT More about constructor/destructor The Big 3 methods in class Class members vs. instance members Constructor vs. destructor ??? static , const Information hiding & access control namespace, cast in C++

    61. ?????????? ??? 61 Class(Object) Constructor 1/4 #include <iostream.h> class Student { // private: long sid; public: showNumber( ) { return sid; } setId( long xx) { sid = xx; } }; int main( ) { Student x, m, n; Student y(456); // Error x.setId(123); return 0; }

    62. ?????????? ??? 62 Class(Object) Constructor 2/4 #include <iostream.h> class Student { // private: long sid; public: showNumber( ) { return sid; } setId( long xx) { sid = xx; } Student(long x) { sid = x; } }; int main( ) { Student x; // Error Student y(456); // OK now x.setId(123); return 0; }

    63. ?????????? ??? 63 #include <iostream.h> class Student { // private: long sid; public: showNumber( ) { return sid; } setId( long x) { sid = x; } Student(long x=0) { sid = x; } }; int main( ) { Student x, y(456); // OK x.setId(123); return 0; }

    64. ?????????? ??? 64 #include <iostream.h> class Student { // private: long sid; public: showNumber( ) { return sid; } setId( long xx) { sid = xx; } Student(long x) { sid = x; cout << "Hehehe\n"; } Student( ) { sid=0; cout << "Haha\n"; } }; int main( ) { Student x, y(456); // OK x.setId(123); return 0; }

    65. ?????????? ??? 65 Constructor ??? Class ????? Constructor ???? type, ????return type Constructor ?? object ????????????, ?????????? (initial value) Student x; //???? x ???????, ??? x.Student( ); Student * p; //??????, ????Student, ????constructor, ? p= new Student( );????constructor

    66. ?????????? ??? 66 The Big 3 methods in class (1/4) ??????????! (????) Default Constructors //???? Copy Constructors //????????reference Assignment Operator Overloading //operator=

    67. ?????????? ??? 67 The Big 3 methods in class (2/4) Default Constructors class A{ }; A x; ??, ? A x( ); ????; ?????? A x(38); ???? ?? .. .. .. ???????????? constructor , ?????? default constructor?????, ?: class B{ public: B(int x) { }; }; ? B mm(38); ?? ? B haha; ? B hehe( ); ?????! ????????????? constructor ???default argument ??

    68. ?????????? ??? 68 The Big 3 methods in class (3/4) (2) Copy Constructors class A{ }; A x; A y = x; ?? A y(x); ?????,?????copy constructor? bitwise copy. ?????? Copy constructor ????

    69. ?????????? ??? 69 The Big 3 methods in class (4/4) (3) Assignment operator= class A{ }; A x; A y; y = x; ??, ????? operator= ? bitwise copy; ?????? operator= ?????!!?????! class A{ public: A& operator=(const A& x){ cout << "hehehe "; }; };

    70. ?????????? ??? 70 Object Destructor #include <iostream> // <iostream.h> using namespace std; class Student { // private: long sid; public: long showNumber( ) { return sid; } void setId( long xx) { sid = xx; } Student(long x) { sid = x; cout << x<<" Hehehe\n"; } Student( ) { sid=38; cout << "Haha\n"; } ~Student( ) { cout << sid<< " Arrrrh ??\n " ; } }; void test( ) { Student x; cout << " ==????== "; } Student xxx(123); int main( ) { cout << " *** ??? *** \n " ; Student y(456); test( ); // ??? test( ) , ???????? return 0; }

    71. ?????????? ??? 71 Output of previous program dtest.cpp mytest/> g++ dtest.cpp mytest/> ./a.out 123 Hehehe *** ???*** 456 Hehehe Haha ==????== 38 Arrrrh ?? 456 Arrrrh ?? 123 Arrrrh ?? mytest/> exit

    72. ?????????? ??? 72 Constructor vs. Destructor Constructor ?????? ???? overloading ???, ?????? ?object????????????????? Destructor ???????, ????? ??????? ??? Class ?????????( ~ )??? ?object?????????????????? ?????? return type Constructor ? Destructor ??? type

    73. ?????????? ??? 73 ??? static On a global variable or a function static long myData[38]; //information hiding static void myFunction(float); Tells the linker not to export the variable or function. Makes the identifier file scope, as the linker will not use it fulfill dependencies from other files. On a local variable in a function void someFunc(void) { static int array[4000]; } Places the variable off the stack. This has the side-effect that it retains it value across calls. It is often used when a variable is too large to be put on the stack. (auto???? stack) On a class member data or member function (next slide)

    74. ?????????? ??? 74 Static class member static member????????object??,????object????member selection operators (?? :: ) ???. (?: Java ?? . ??class member ? instance member ???????) Static member functions Also known as class function (class methods) Can be called without any instance, for example: m = Mankind::howmany( ); // ? ?? C++ ?? Can NOT access instance variables Static member data Also known as class variable All objects of a class share one copy of a static data member (non-static member data = instance variable) Usage example: x = Mankind::data_which_is_static; They are not global variables; they have class scope

    75. ?????????? ??? 75 ??? const Const object is NOT modifiable const x = 3.14159; // ? C ???C++ compile??;?????? Const parameter can NOT be modified in the function ReturnType FunctionName(long x, const Student y){ /* to modify y is NOT allowed! ? y ????? */ }; Const member function can NOT modify the object ReturnType FunctionName(param1,param2) const; ReturnType FunctionName(param1,param2) const { /* */}; Constructors / Destructors cannot be const They need to initialize variables (therefore modifying them)

    76. ?????????? ??? 76

    77. ?????????? ??? 77 Information hiding (???? 2/3 ) class Animal{ // private: long height; double hehe; public: Animal( ); float weight; void talk( ) { /***/ } }; Animal::Animal( ) { height=170; hehe =38.49; weight = 59.66; }

    78. ?????????? ??? 78 Information hiding (???? 3/3 ) class Animal{ long height; double hehe; public: Animal( ); float weight; void talk( ) { /***/ } friend int main ( ); }; Animal::Animal( ) { height=170; hehe =38.49; weight = 59.66; }

    79. ?????????? ??? 79 Information Hiding Summary 3 access control clauses for class members private: clause for hidden entities public: clause for interface entities protected: clause - for inheritance (extension) friend functions or classes - to provide access to private members in some unrelated program units or functions friend functions are not member functions of class Defined outside of class scope if B a friend of A, A not necessarily a friend of B

    80. ?????????? ??? 80 Namespaces (1/2) Namespaces allow us to group a set of global classes, objects and/or functions under a name. In other words they serve to split the global scope in sub-scopes known as namespaces. The form to use namespaces is: namespace identifier { namespace-body }

    81. ?????????? ??? 81 Namespaces (2/2) variables with same name and different scopes can overlap need to distinguish them a namespace defines a scope for local and global identifiers. body delimited by braces {} use (::) to access namespace members: namespace_name::member or, a using statement must occur before name is used using namespace namespace_name; -members of the namespace do not need a prefix not guaranteed to be unique can be nested All of the standard C++ libraries are contained in the std namespace.

    82. ?????????? ??? 82 When variables of one type are mixed with another Type Conversion occurs automatically. This is not possible in Java (where casting is needed), and would cause an error. int main() { int x; char ch; float f; // ch = x; x = f; f = x; } Type coercion

    83. ?????????? ??? 83 Cast in C++ C++ has 4 more separate, specific casts Conventional static cast (C-Style): (type)expression static_cast - conversion between types type checking at compile time standard conversions: void* to char*, int to float, etc. base class pointers to derived class pointers Format: static_cast<type to convert to>(object to convert) const_cast - cast away const or volatile cannot be used directly to cast away const-ness; use pointers dynamic_cast for safe navigation of an inheritance hierarchy. Can be used only for pointer or reference types reinterpret_cast - for nonstandard casts one pointer type to another pointer type, void* to int*, etc. cannot be used for standard casts (int to double, etc.).

    84. ?????????? ??? 84 More tips about C++ (1/3) C++ ????????? (???) ??? ? ?? ????????? block ?????, C99 ???????? int main( ) { int m, n; /* all OK */ m=2, n=3; float x; /* ????? C ??????, ?? C++ ? C99 ???? */ }

    85. ?????????? ??? 85 More tips about C++ (2/3) C++???? ??C++????????????;?????????? C++ ? Reference used in program other than in parameters double salary; double& pay = salary; /* ?????? */ /* ??? pay ?? salary ???? */ salary = 49; pay = 38; /* ???? salary ?? 38 */

    86. ?????????? ??? 86 More tips about C++ (3/3) C++ ????? reference ??? ????????????????? reference ??????:

    87. ?????????? ??? 87 Thank You! ???? tsaiwn@csie.nctu.edu.tw ???

    88. ?????????? ??? 88 ?????????? (1/8) ????, ????! ??? user ????? (why? ) (1) ????/????? #include <stdio.h> (2) ????: printf("%f", number); ??? number ?? float ??? double ???? C ???? float ????? double ??? (3)????: printf("%d", number); ??? number ? int; ??long??%ld; ??short?%hd (4)????: scanf("%f %lf", &numfloat, &numdouble); ??? numfloat ? float; numdouble ? double; (5)????????? long ?? "%ld", int ? "%d", short?"%hd" (6)???????scanf ?????? printf ????! printf ? float ? double ?? %f ?? scanf ? sscanf ??? double ?? "%lf", float ? "%f"

    89. ?????????? ??? 89 ?????????? (2/8) ?????? user ?????, ?: ??????? fgets ?? buffer ????, ????? scanf static char buf[999]; int age; fprintf(stderr, "?????: "); fgets(buf, sizeof(buf), stdin); /* ???????gets(buf); */ sscanf(buf, "%d", &age); /* ? buf ? scan */ ?????????? age = atol(buf); /* ?? */ ?? age = atof(buf); /* double or float ?? */

    90. ?????????? ??? 90 ?????????? (3/8) ???? gets static char buf[99]; gets(buf); /* ????? 99 char ???? */ ? /* ??????? ? */

    91. ?????????? ??? 91 ?????????? (4/8) ???? (File I/O) OS_level: 0 ?, 1?, 2? ???? C?????: stdin, stdout, stderr C++ ?????: cin, cout, cerr Java ?????: System.in, System.out, System.err System.class ??? static class ? class ??????: in, out, err

    92. ?????????? ??? 92 ?????????? (5/8) ? C ?????? (File I/O) FILE * fp; fp = fopen("filename.ext", "rt"); /*?????? "rt", ??? "wt" */ if(fp==0) /*??? open ???? ... */ fgets(buf, sizeof(buf), fp); /* buf ? char array */ fscanf ??? sscanf, ???????? fp fprintf ???? sprintf, ???????? fp (sprintf ?????? char array)

    93. ?????????? ??? 93 ?????????? (6/8) ?? C ?????? binary file fread ? fwrite FILE * fp; /* FILE ??? struct */ fp = fopen("filename.ext", "rb"); fread(buf, 1, sizeof(buf), fp); /* buf ? char array */ fclose(fp); fp = fopen("filename.ext", "wb"); fwrite(buf, 1, sizeof(buf), fp); /* buf ? char array */ *** ??? man fseek, man fscanf ? man fgetc ?? see ALSO ...

    94. ?????????? ??? 94 ?????????? (7/8) ? C++ ?????? (File I/O) ?? fstream, ifstream, ofstream ifstream myf("ggg.dat"); myf.getline(buf, sizeof(buf); // ?????? // ?????? C ??????? //?????: myf >> mydata; //??(?)

    95. ?????????? ??? 95 ?????????? (8/8) ?????? gets ???? fgets ??? ????! ? fgets( ) ???????? newline ???????? void chop(char*x) ??? x ??? newline ? ? cin.getline(buf, sizeof(buf)); ??????? gets(buf); ???, ????? newline ?? data ?? sscanf ??? strtok ?? strtok( ) function ??thread????, ??????? C ?? strsep( )

    96. ?????????? ??? 96 Writing data to a file (1/2)

    97. ?????????? ??? 97 Writing data to a file (2/2)

    98. ?????????? ??? 98 File access modes

    99. ?????????? ??? 99 C++ I/O Library (1/8) Input/Output in C++ Performed with streams of characters Streams sent to input/output objects Input std::cin - standard input object (connected to keyboard) >> stream extraction operator ("get from") std::cin >> myVariable; Gets stream from keyboard and puts it into myVariable Output std::cout - standard output stream (connected to screen) << stream insertion operator ("put to") std::cout << "hi"; Puts "hi" to std::cout, which prints it on the screen std::cerr - standard error report stream (connected to screen)

    100. ?????????? ??? 100 C++ I/O Library (2/8) std::endl "end line" Stream manipulator - prints a newline and flushes output buffer Some systems do not display output until "there is enough text to be worthwhile" std::endl forces text to be displayed std::cout << std::endl; using namespace statements Allow us to remove the std:: prefix using namespace std; // ???????? std:: Cascading Can have multiple << or >> operators in a single statement std::cout << "Hello " << "there" << std::endl;

    101. ?????????? ??? 101 C++ I/O Library (3/8) iostream library: <iostream>: Contains cin, cout, cerr, and clog objects <iomanip>: Contains parameterized stream manipulators <fstream>: Contains information important to user-controlled file processing operations

    102. ?????????? ??? 102 C++ I/O Library (4/8) cin.get(): inputs a character from stream (even white spaces) and returns it cin.get( c ): inputs a character from stream and stores it in c cin.get(array, size): Accepts 3 arguments: array of characters, the size limit, and a delimiter ( default of \n). Uses the array as a buffer When the delimiter is encountered, it remains in the input stream Null character is inserted in the array Unless delimiter flushed from stream, it will stay there cin.getline(array, size) Operates like cin.get(buffer, size) but it discards the delimiter from the stream and does not store it in array Null character inserted into array

    103. ?????????? ??? 103 C++ I/O Library (5/8) ignore member function Skips over a designated number of characters (default of one) Terminates upon encountering a designated delimiter (default is EOF, skips to the end of the file) putback member function Places the previous character obtained by get back in to the stream. peek Returns the next character from the stream without removing it read and write member functions Unformatted I/O Input/output raw bytes to or from a character array in memory Since the data is unformatted, the functions will not terminate at a newline character for example Instead, like getline, they continue to process a designated number of characters If fewer than the designated number of characters are read, then the failbit is set Stream manipulators: oct, hex, dec, setbase( ), setprecision( ), setw( )

    104. ?????????? ??? 104 C++ I/O Library (6/8) ifstream Suppose we need an input stream fin for extracting values from the file scores.dat first include the <fstream> library. The desired stream can be created by defining an ifstream object fin as follows: ifstream fin(scores.dat); The supplied parameter must be a null terminated string, showing the librarys old c routes. However strings have a method called .c_str() that will convert them to this format. The following statement extracts information from scores.dat: fin >> value; ifstream is derived from istream we can use the >> operator for ifstream objects.

    105. ?????????? ??? 105 C++ I/O Library (7/8) ofstream If we define an ofstream object we can use it to capture insertions to a file. ofstream fout(results.txt); fout << value; The above code simply associates the the ofstream object fout with the file results.txt, and then inserts a value into that file. By default the file associated with ofstream object will be made empty during initialisation.

    106. ?????????? ??? 106 C++ I/O Library (8/8) open( ) and close( ) member function Objects of type ifstream and ofstream have several member functions. close() and open()are two of these. close() indicates that the processing of the associated file is complete. conceptually open() has two versions, both requiring a character string, but one version also allows a parameter to specify the mode. (see next slides for various open modes)

    107. ?????????? ??? 107 ios flags for open Mode

    108. ?????????? ??? 108 <iomanip> functions setw(int w) setfill(int c) left right setbase(int b) fixed scientific showpoint setprecision(int d) skipws showpos boolalpha

    109. ?????????? ??? 109 man fork FORK(2) FreeBSD System Calls Manual FORK(2) NAME fork -- create a new process LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <sys/types.h> #include <unistd.h> pid_t fork(void); DESCRIPTION fork( ) causes creation of a new process. The new process (child process) is an exact copy of the calling process (parent process) except

    110. ?????????? ??? 110 fork( ) example switch(pid=fork( ) ) { case -1: syslog("Fork failed"); free(nchunk); close(null); close(fd[0]); close(fd[1]); return NULL; case 0: /* child */ signal(SIG_TSTP, SIG_IGN); /* Stop TSTP */ close(fd[0]); close(0); close(1); close(2); dup2(null,0); dup2(fd[1],1); dup2(null,2); exec("/usr/bin/ps", "ax"); exit(0); /* Should never get here */ default: /* original parent process */ close(fd[1]); close(0); break; /* */

    111. ?????????? ??? 111 man pthread PTHREAD(3) FreeBSD Library Functions Manual PTHREAD(3) NAME pthread -- POSIX thread functions SYNOPSIS #include <pthread.h> DESCRIPTION POSIX threads are a set of functions that support applications with requirements for multiple flows of control, called threads, within a process. Multithreading is used to improve the performance of a program. The POSIX thread functions are summarized in this section in the following groups: Thread Routines Attribute Object Routines Mutex Routines Condition Variable Routines Read/Write Lock Routines Per-Thread Context Routines Cleanup Routines

    112. ?????????? ??? 112 Multithread Multithreading means that a single process can perform many tasks simultaneously, which becomes very handy when you have lot of conceptual independent jobs to do (like processing connections from several clients if you're a web server program) that each might lead to temporary block of the job (i.e. waiting for a response from the current client). All those task will run the same program, and will share some data but they also have a separate state each - thus a private copy of CPU registers, a private program counter and a private stack with GLocal variables.

More Related