41
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

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

Embed Size (px)

Citation preview

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.8Id: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

files (example)#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.tx

t");outfile.open("tax.txt");while (infile

>>income ){ if (income <cutoff )

tax =rate1 *income;elsetax =rate2 *income;outfile<<"Income="<<inco

me <<"greenbacks \n" <<"Tax ="<<tax <<"greenbacks \n";}infile.close();outfile.close();return 0;}

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 sucessfullyorif (!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 lengthstring 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

getline function example (copy file)

#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;

}

22

the type string

input a line of string from cinstirng s;getline(cin, s);

concatenation of stringstring 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

[ ] operatorstring 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

call by reference

#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( )

ti a

j b

7

-3

i=-3 j=7

29

call by reference in C (use pointer)

#include <stdio.h>void swap(int*, int*); // function prototypemain( ) { 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 insteadint t; // of reference variablest = *a; *a = *b; *b=t; // use pointers to reference the } // values in main function

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 invocationf(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

overloading functions

#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’;

}

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

dynamic allocation

#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;

}

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

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; }}

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

exception handling

try-throw-catch clausetry {

… // regular statements

throw an_exception;

}

catch (exception1) { … } // exception handlers

catch (exception2) { … }

40

exception handling

exampleint* 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