1 / 41

Object oriented programming

Object oriented programming. What is Class? What is Object? From object-oriented point of view Class is a user-defined data type which contains relevant data and functions Object is a variable declared under some class data type From philosophy concept

kuniko
Download Presentation

Object oriented programming

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. Object oriented programming • What is Class? What is Object? • From object-oriented point of view • Class is a user-defined data type which contains relevant data and functions • Object is a variable declared under some class data type • From philosophy concept • Class is an abstract concept that describes the attributes of a collection of objects

  2. From C to C++ • Namespace • 變數、函數、或物件所屬的空間名稱,在不同的namespace中可使用相同的變數名稱。 • std: C++所有系統提供的函數所屬的namespace • avoid conflict of variable names in the different class libraries

  3. namespace example //This program outputs the message // //C++:one small step for the program, //one giant leap for the programmer // //to the screen #include <iostream> using namespace std; int main(){ cout <<"C++:one small step for the program,\n" <<"one giant leap for the programmer \n"; return 0; } • compare to C: • #include <stdio.h> • main( ){ • printf(“….”); • without namespace

  4. namespaces • create namespace • examples: namespace mfc{ int inflag; void g(int); … } namespace owl{ int inflag; … }

  5. namespace • use variables in a namespace • use scope resolution operator :: • e.g. mfc::inflag = 3; owl::inflg = -823; cout << mfc::inflag; • the using directive • e.g.. using namespace mfc; inflag = 3; // 相當於 mfc::inflag = 3; owl::inflag = -823;

  6. C++ Input/Output • C++ Input/Output objects • cin standard input • cout standard output • cerr standard error • e.g. cin >> x; cin >> len; cout << x; cout << len; cin >> x >> len; cout << x << len;

  7. C++ Input/Output • example #include <iostream> using namespace std; int main( ) { int id; float av; cout << “Enter the id and the average:”; cin >> id >> av; cout << “Id:” << id << ‘\n’ << “Average:” << av << ‘\n’; return 0; } Enter the id and the average:900038 90.8 Id:900038 Average:90.8

  8. C++ Input Output • Manipulators • for the format of I/O • set width to n: setw(n) for (i=1; i<=1000; i*=10) cout << setw(6) << i << ‘\n’; 1 10 100 1000

  9. manipulators • endl: end of line, write new line • e.g. int i=4, j=6, k=8; char c=‘!’; cout << i << c << endl << j << c <<‘\n’ << k << c << endl; 4! 6! 8!

  10. manipulators • oct (octal), hex(hexadecimal), dec(decimal) • e.g. int i = 91; cout << “i=“ << i << “ (decimal)\n”; cout << “i=“ << oct << i << “ (octal)\n”; cout << “i=“ << hex << i << “ (hexadecimal)\n”; cout << “i=“ << dec << i << “ (decimal)\n”; i=91 (decimal) i=133 (octal) i=5b (hexadecimal) i=91 (decimal)

  11. manipulators • listed in Figure 2.2.2 • dec, endl, fixed, flush, hex, left, oct, right, scientific, setfill( c ), setprecision(n), setw(n), showpoint, noshowpoint, showpos, noshowpos, skipws, noskipws, ws

  12. manipulators • setfill, setprecision • e.g. float a = 1.05, b=10.15, c=200.87; cout << setfill(‘’) << setprecision(2); cout << setw(10) << a << ‘\n’; cout << setw(10) << b << ‘\n’; cout << setw(10) << c << ‘\n’; ******1.05 *****10.15 ****200.87

  13. #include <fstream> using namespace std; const int cutoff =6000; const float rate1 =0.3; const float rate2 =0.6; int main(){ ifstream infile; ofstream outfile; int income,tax; infile.open("income.txt"); outfile.open("tax.txt"); while (infile >>income ){ if (income <cutoff ) tax =rate1 *income; else tax =rate2 *income; outfile<<"Income="<<income <<"greenbacks \n" <<"Tax ="<<tax <<"greenbacks \n"; } infile.close(); outfile.close(); return 0; } files (example)

  14. files (example cont.) input file “income.txt” 2214 10500 31010 result: output file “tax.txt” Income = 2214 greenbacks Tax= 664 greenbacks Income = 10500 greenbacks Tax= 6299 greenba cks Income = 31010 greenbacks Income = 18605 greenbacks

  15. files • testing whether files are open • file object converts to ‘true’ if open successfully, otherwise converts to ‘false • e.g. ifstream infile; ifstream.open(“scores.dat”); … if (infile) { … } // if open sucessfully or if (!infile) { … } // if fail to open the file

  16. files • e.g.. ifstream infile; infile.open(“scores.dat”); if (!infile) { cerr << “Unable to open scores.dat\n”; exit(0); }

  17. C++ features • bool data type • values: true (1) or false(0) • manipulators: boolalpha, noboolalpha (default) • e.g. bool flag; flag = (3 < 5); cout << flag << ‘\n’; cout << boolalpha << flag << ‘\n’; 1 true

  18. the type string • string initialization • e.g. #include <string> string s1; string s2 = “Bravo”; string s3 = s2; string s4(10,’x’); cout << s1 << ‘\n’; cout << s2 << ‘\n’; cout << s4 << ‘\n’; Bravo xxxxxxxxxx

  19. the type string • C-style string (end with a null char ‘\0’) char mystring = “a string”; or char mystring[ ] = “a string”; printf(“%s\n”, mystring); char mystring[9] • the null character ‘\0’ is added by the C compiler automatically a s t r i n g \0

  20. the type string • string length string s = “Ed Wood”; cout << “Length=“ << s.length( ) << ‘\n’; • input a string • separate by space or new line cout << “Enter a string:”; cin >> s; cout << s; Length=7 Ed Wood Ed

  21. #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ string buff; ifstream infile; ofstream outfile; cout << “Input file name:”; cin >> buff; infile.open(buff.c_str()); cout << “Output file name:”; cin >> buff; outfile.open(buff.c_str()); while (getline(inflie, buff)) outfile <<buff<<“\n\n”; infile.close(); outfile.close(); return 0; } getline function example (copy file)

  22. the type string • input a line of string from cin stirng s; getline(cin, s); • concatenation of string string s1=“Atlas ”, s2=“King”, s3; s3 = s1 + s2; cout << s1 << ‘\n’; cout << s2 << ‘\n’; cout << s3 << ‘\n’; Atlas King Atlas King

  23. the type string • remove a substring • s.erase(position, length); • e.g. string s = “Ray Dennis Steckler”; s.erase(4, 7); cout << s << ‘\n’; Ray Steckler

  24. the type string • insert a string • s.insert(position, str2); • replace a substring • s.replace(startpos, length, str2); • swap strings • s1.swap(s2); • extract a substring • s.substr(position, length)

  25. the type string • [ ] operator string s = “Nan” cout << s[1]; << ‘\n’; s[0] = ‘J’; cout << s << ‘\n’; • search a substring • s1.find(s2, position); • compare strings • == , !=, <, >, <=, >= a Jan

  26. functions • reference variables • provides an alternative name for storage • e.g. memory int x; int& ref=x; x ref x = 3; cout << ref; 3

  27. functions • call by value (default in C) • pass values to the called function • call by reference • pass addresses to the called function • provided in C++, but not in C • e.g. void swap(int&, int&);

  28. #include <iostream> using namespace std; void swap(int&, int&); int main( ) { int i=7, j=-3; swap(i, j); cout << “i=“ << i << ‘\n’ << “j=“ << j << ‘\n’; return 0; } void swap(int& a, int& b) { int t; t=a; a=b; b=t; } pass address of i, j to a,b main( ) swap( ) t i a j b call by reference i=-3 j=7

  29. #include <stdio.h> void swap(int*, int*); // function prototype main( ) { int i=7, j=-3; swap(&i, &j); // passing addresses of i and j printf(“i=%d j=%d”, i,j); } void swap(int* a, int* b) { // use pointers parameters instead int t; // of reference variables t = *a; *a = *b; *b=t; // use pointers to reference the } // values in main function call by reference in C (use pointer)

  30. functions • default arguments • all the parameters without default values must come first in the parameter list. • better to specify in the prototype, e.g. void f(int val, float s=12.6, char t=‘\n’, string msg=“Error”); • valid invocation f(14, 48.3, ‘\t’, “ok”); // s=48.3, t=‘\t’, msg=“ok” f(14, 48.3); // s=48.3, t=‘\n’, msg=“Error” f(14); // s=12.6, t=‘\n’, msg=“Error”

  31. functions • overloading functions • functions can have the same name, but • function signatures need to be distinct • function name • number, data type, and order of it arguments • e.g. void print(int a); void print(double a); // o.k. void print(int a, int b); // o.k. int print(int a); // wrong! return type is not part of signatures

  32. #include <iostream> #include <iomanip> void print(int a); void print(double a); int main( ){ int x=8; double y=8.0; print(x); print(y); return 0; } void print(int a) { cout << a << ‘\n’; } void print(double a) { cout << showpoint << a <<‘\n’; } overloading functions 8 8.000

  33. dynamic (vs. static)allocation • dynamic allocation • pointer_var = new data-type; // single data • pointer_var = new data-type[size]; // array • e.g. int* int_ptr; int_ptr = new int; ptr int* ptr; ptr = new int[100]; ptr[0] ptr[1] … ptr[99] …

  34. dynamic allocation • delete, delete[ ] • free storage allocated by new or new type[size] • e.g. delete int_ptr; delete[ ] ptr; • linked list example name next start ‧‧‧ “林旺” “馬蘭” “阿美” 0

  35. #include <string> using namespace std; struct Elephant { string name; Elephant* next; }; void print_elephants(const Elephant* ptr ); Elephant* get_elephants( ); void free_list(const Elephant* ptr ); int main( ) { Elephant* start; start =get_elephants( ); print_elephants(start ); free_list(start ); return 0; } dynamic allocation

  36. Elephant* get_elephants( ){ Elephant *current,*first; int response; current =first =new Elephant; cout <<"\nNAME:"; cin >>current ->name; cout <<"\nAdd another?(1 ==yes, 0 ==no):"; cin >>response; //Add Elephants to list until user signals halt. while (response ==1 ){ current =current ->next =new Elephant; cout <<"\nNAME:"; cin >>current ->name; cout <<"\nAdd another?(1 ==yes, 0 ==no):"; cin >>response; } current ->next =0; return first; } dynamic allocation

  37. void print_elephants(const Elephant* ptr ){ int count =1; cout <<"\n \n \n"; while (ptr !=0 ){ cout <<"Elephant number“ <<count++ <<"is "<<ptr ->name <<’\n ’; ptr =ptr ->next; } } void free_list(const Elephant* ptr ){ const Elephant* temp_ptr; while (ptr !=0 ){ temp_ptr =ptr ->next; delete ptr; ptr =temp_ptr; } } dynamic allocation

  38. struct Elephant { string name; Elephant* next; }; first current current->name current->next Elephant * start; … Elephant *current,*first; current =first =new Elephant; current =current ->next =new Elephant; dynamic allocation

  39. exception handling • try-throw-catch clause try { … // regular statements throw an_exception; … } catch (exception1) { … } // exception handlers catch (exception2) { … } …

  40. exception handling • example int* ptr; try { ptr = new int; // throw bad_alloc exception if ‘new’ failure … } catch (bad_alloc) { cerr << “new: unable to allocate storage!\n”; exit(0); } …

  41. homework #2 (1). 執行課本Example 2.7.1的程式(p.71),輸入至少10隻象的名字。 (2). 加入一新的function名為reverse_elephant至Example2.7.1中,其function prototype如下: Elephant* reverse_elephant(Elephant* start); 此function的功能在於建立一新linked list,將原以start為起點的linked list中的資料做反向連結,然後傳回此新的linked list的起始位置的pointer值 ;並在main function中至少重複呼叫reverse_function兩次,用以驗證你的程式的正確性。例如: 原: start … 經reverse_elephant後: rstart … elp1 elp2 elpn 0 elpn elp2 elp1 0

More Related