Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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

3 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 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 main( ){ printf(“….”); without namespace

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

5 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 6 C++ Input/Output C++ Input/Output objects - cin standard input - coutstandard output - cerrstandard error - e.g. cin >> x; cin >> len; cout << x; cout << len; cin >> x >> len; cout << x << len;

7 7 C++ Input/Output example #include 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 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 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 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 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 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 13 files (example) #include 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; }

14 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 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 16 files - e.g.. ifstream infile; infile.open(“scores.dat”); if (!infile) { cerr << “Unable to open scores.dat\n”; exit(0); }

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

19 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 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 21 getline function example (copy file) #include 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; }

22 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 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 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 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 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 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 28 call by reference #include 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 7 -3 i=-3 j=7

29 29 call by reference in C (use pointer) #include 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

30 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 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 32 overloading functions #include 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’; } 8 8.000

33 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 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 35 dynamic allocation #include 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; }

36 36 dynamic allocation 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; }

37 37 dynamic allocation void print_elephants(const Elephant* ptr ){ int count =1; cout <<"\n \n \n"; while (ptr !=0 ){ cout <<"Elephant number“ <<count++ 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; }

38 38 dynamic allocation 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;

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

40 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 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 … elp1elp2elpn 0 elpnelp2elp1 0


Download ppt "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."

Similar presentations


Ads by Google