420 likes | 524 Views
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
E N D
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
From C to C++ • Namespace • 變數、函數、或物件所屬的空間名稱,在不同的namespace中可使用相同的變數名稱。 • std: C++所有系統提供的函數所屬的namespace • avoid conflict of variable names in the different class libraries
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
namespaces • create namespace • examples: namespace mfc{ int inflag; void g(int); … } namespace owl{ int inflag; … }
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;
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;
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
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
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!
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)
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
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
#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)
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
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
files • e.g.. ifstream infile; infile.open(“scores.dat”); if (!infile) { cerr << “Unable to open scores.dat\n”; exit(0); }
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
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
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
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
#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)
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
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
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)
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
functions • reference variables • provides an alternative name for storage • e.g. memory int x; int& ref=x; x ref x = 3; cout << ref; 3
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&);
#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
#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)
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”
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
#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
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] …
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
#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
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
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
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
exception handling • try-throw-catch clause try { … // regular statements throw an_exception; … } catch (exception1) { … } // exception handlers catch (exception2) { … } …
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); } …
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