60
交交交交 交交交 MoreConcepts-1 More Programming Concept 蔡蔡蔡 [email protected] 蔡蔡蔡蔡蔡蔡蔡蔡蔡蔡

More Programming Concept

  • Upload
    gada

  • View
    45

  • Download
    0

Embed Size (px)

DESCRIPTION

More Programming Concept. 蔡文能 [email protected] 交通大學資訊工程學系. Agenda. Variable and memory Array vs. pointer More about for Loop C++ string I/O and File handling Other topics. Auto 變數不可佔太多 memory. Auto 變數就是沒寫 static 的 Local 變數 Auto 變數 是在 進入函數時 才在 STACK 區 安排記憶體 , - PowerPoint PPT Presentation

Citation preview

Page 1: More Programming Concept

交大資工 蔡文能 MoreConcepts-1

More Programming Concept

蔡文能[email protected]交通大學資訊工程學系

Page 2: More Programming Concept

交大資工 蔡文能 MoreConcepts-2

Agenda

• Variable and memory

• Array vs. pointer

• More about for Loop

• C++ string

• I/O and File handling

• Other topics

Page 3: More Programming Concept

交大資工 蔡文能 MoreConcepts-3

Auto 變數不可佔太多 memory•Auto 變數就是沒寫 static 的 Local 變數•Auto 變數是在進入函數時才在 STACK 區安排記憶體 ,

在離開函數 (return) 時就還掉 ( 改變 Stack Pointer)

•STACK 區一般不會很大 ( 幾拾 K Bytes)– Auto 變數用 STACK 區 , 所以太大的 array 不能用– 叫用函數時 , return address 也會被推入 STACK

– 參數傳遞也是用 STACK 區– C/C++ 推入參數時是先推入最後一個參數 , 這使得第

一個參數會在堆疊的最上方 , 進入函數時 , STACK 中 return address 之下就是第一個參數

– C/C++ 離開函數時 , 函數不負責拿掉 STACK 中 的參數 , 那是叫用函數那個程式的責任 ! ( 與其它語言不同 )

Page 4: More Programming Concept

交大資工 蔡文能 MoreConcepts-4

Auto 變數佔用 STACK 區 memory

•Auto 變數就是沒寫 static 的 Local 變數

CPUIP

SP

Instruction Pointer

Stack Pointer

系統區

系統區

程式 + 靜態 data

HEAP 堆積STACK

Page 5: More Programming Concept

交大資工 蔡文能 MoreConcepts-5

Static 變數 ?•Global 變數都是 static 的 變數•Local 變數就是在函數內的變數

– 有補 static 修飾詞則為 static 變數– 沒有補 static 修飾詞則為 Auto 變數

•static 的 變數在程式開始 RUN 之前就存在 , 且已經設好初值 , 程式結束後才會還掉所佔記憶體•寫了 extern 表示只是 宣告 , 不是定義 (define)•Local 變數就只能在該函數內存取•Global 變數則只要看得見它的任一函數都能存取它

– 宣告之後就看得見 , 沒宣告就定義 則看作 同時宣告了•注意 main( ) 也是函數 , 沒有特別偉大 !

Page 6: More Programming Concept

交大資工 蔡文能 MoreConcepts-6

Global, Static Local, Auto 變數 #include <stdio.h>

extern int x; /* 只有宣告 , 還不知道位置在何處 ?*/

int fa( ) ;

int fb( ) { int ans=0; return ++ans; }

int main( ) {

int kk=123;

cout << "fa( )=" << fa( )<<fa( )<<fa( ) << kk<<endl;

cout << "fb( )=" << fb( )<<fb( )<<fb( ) << endl;

return 0; /* 0 in main( ) means OK */

}

int x, y; /* 真的 x 在這 , 也可以寫在另一個 file 中 */

int fa ( ) { /*…* }

寫了 extern 表示只是 宣告 , 不是定義 (define)

Page 7: More Programming Concept

交大資工 蔡文能 MoreConcepts-7

Static Global 變數 #include <stdio.h>

#define BUFSIZE 100

static char buf[BUFSIZE];

static int bufp = 0;

int getch( ) {

/* . . . */

}

void ungetch(int c) {

/* . . . */

}

參考 K&R 課本 4.6節

也參考 stack 的 push 和 pop 寫在同一獨立 file 中 , push 和 pop 共享 data

Page 8: More Programming Concept

交大資工 蔡文能 MoreConcepts-8

再談 Static Global 變數 #include <stdio.h>

#define RAND_MAX 65535

static unsigned long seed=0; /* global */

int rand( ) {

seed = seed * 1103515245 + 12345;

return seed % (RAND_MAX+1);

}

void srand(int newseed) {

seed = newseed;

}

參考 K&R 課本 4.6節

Pseudo random number

Page 9: More Programming Concept

交大資工 蔡文能 MoreConcepts-9

register 變數 , volatile 變數 #include <stdio.h>

enum {BUFSIZE=100, NSTU=60};

register int wrong; /* this is wrong, global 不可 */

volatile int haha;

void myfun(register int x ) {

register int yy, i; /* OK */

int * p;

/* . . . */

p = &yy; /* this is wrong */

} 參考 K&R 課本 4.7節

Page 10: More Programming Concept

交大資工 蔡文能 MoreConcepts-10

volatile 變數 #include <stdio.h>

volatile int haha ; /* tell compiler … */

int main( ) {

int k; double ans;

for(k=1; k<=99; ++k) { /* . . . */

ans = haha * haha; /* do not optimize*/

printf(" ans=%f\n ", ans);

}

} 參考 K&R 課本 4.7節

Page 11: More Programming Concept

交大資工 蔡文能 MoreConcepts-11

再談 Array 與 pointer

short int x[ ] = { 0, 1, 2, 3, 4, 5, 6, 7 };

long * p = x; /* 意思是 p = &x[0]; */

long ans;

int main( ) {

ans = *p; /* 同 : ans = p[0]; */

printf("ans=%ld, p2=%ld\n", ans, p[2]);

} 注意 byte order, big endian vs. little endian

p[2] 與 *(p+2) 完全相同

pointer 本身是 一個整數指向別的記憶體

Page 12: More Programming Concept

交大資工 蔡文能 MoreConcepts-12

再論 for Loop

• for 之中規中矩用法– 就是明顯在數 (count) loop 次數– ( 若不知要 Loop 幾次則建議用 while )

• for 與 array 配合使用– Pascal Triangle– Magic Square

• 順便做些事的 for

Page 13: More Programming Concept

交大資工 蔡文能 MoreConcepts-13

for 之中規中矩用法• 強掉 loop 次數 : 以下四例都是做 9 次

for ( i=1; i<= 9; ++i) /* … */ ;for ( i=1; i<= 9; i++) /* … */ ;

for( i=1; i<10; ++i) /* … */ ;for( i=1; i<10; i++) /* … */ ;

參考之前 9x9 乘法表 , Pascal 三角形

Page 14: More Programming Concept

交大資工 蔡文能 MoreConcepts-14

for 與 array 配合使用• 仔細看 Pascal triangle 例子

– Using Two dimensional array– Using one dimensional array

• 仔細看 Magic Square 例子– 注意奇數階魔方陣之做法轉個想法就變成可

直接用雙層 for loop– 注意 4 的倍數階魔方陣之重點在如何判斷

某格子是否在所謂的對角線上

Page 15: More Programming Concept

交大資工 蔡文能 MoreConcepts-15

再看 4k 階的魔方陣• 4 的倍數階 Magic Square 之重點在如何

判斷該格子 x[row][col] 是否在對角線上– 注意畫對角線時是每個 4 x 4 方陣為單位– 但填入數值時是以整個方陣由左而右由上而

下填入 1 到最後一個數 (next slides)– Index 由 0 算起與由 1 算起要如何調整 ?

( C/C++/Java 語言 index 是由 0 算起 )

Page 16: More Programming Concept

交大資工 蔡文能 MoreConcepts-16

順便做些事的 for loop (1/ 4)

• K&R 1.5.1 檔案複製 int c;

c= getchar( );

while( c!= EOF) {

putchar(c);

c = getchar( );

}

#define EOF (-1)

• int c;

c= getchar( );

for ( ;c!= EOF;) {

putchar(c);

c = getchar( );

}

Page 17: More Programming Concept

交大資工 蔡文能 MoreConcepts-17

順便做些事的 for loop (2/ 4)

• int c;

for (c= getchar( ) ; c!= EOF ; c = getchar( ) ) {

putchar(c);

}

Page 18: More Programming Concept

交大資工 蔡文能 MoreConcepts-18

順便做些事的 for loop (3/4 )• 1.5.2 Counting characters long nc;

nc= 0;

while ( getchar()!= EOF) ++nc;

/* … * long nc;

nc= 0;

for (nc=0; getchar()!= EOF; ++nc)

;

/* … *

Page 19: More Programming Concept

交大資工 蔡文能 MoreConcepts-19

順便做些事的 for loop (4/4 )

• K&R 1.9 統計 file 中出現各字• K&R 2.6

• K&R 2.7 atoi

• K&R 2.8 squeeze

• K&R 3.5 atoi

• K&R 3.7 trim

• K&R 4.2 atof

Page 20: More Programming Concept

交大資工 蔡文能 MoreConcepts-20

<algorithm> <bitset> <complex> <deque>

<exception> <fstream> <functional> <iomanip>

<ios> <iosfwd> <iostream> <istream>

<iterator> <list> <locate> <limits>

<map> <memory> <new> <numeric>

<ostream> <queue> <streambuf> <string>

<set> <sstream> <stack> <stdexcept> <typeinfo> <utility> <valarray> <vector>

<cmath>

C ++ class Library

Page 21: More Programming Concept

交大資工 蔡文能 MoreConcepts-21

The C++ String Class

• The C-style strings (arrays of char) that you’ve been using are not the only way of managing character data.

• C++ allows you to work with a string class that eases many of the problems you’ve encountered with C-style strings.

• In particular, you don’t have to worry about managing memory for the string data.

Page 22: More Programming Concept

交大資工 蔡文能 MoreConcepts-22

C++ String Basics• The basic character template class is basic_string<>.• It has two specializations (generated using typedefs), strin

g and wstring.• string corresponds to the C-style string (I.e., const *char).• wstring is an extension for languages that use characters.• You can copy, assign, and compare strings just like you w

ould copy, assign, and compare primitive types (int, double)

string a = “Hello”; string b = string(a); string c = a; bool d = (a==b);

Page 23: More Programming Concept

交大資工 蔡文能 MoreConcepts-23

using the String types• In the header file <string>

– (Note, no .h)

• All such functions and other names are in the namespace std.

• The basic class name is a template class, basic_string<>.• String constructors

string( ) // emptystring(string s) // copy of sstring(string s, int start) // substringstring(string s, int start, int len) // substringstring(char* a) // C-stringstring(int cnt, char c) // one or more charsstring(char* beg, char* end) // [beg, end)

Page 24: More Programming Concept

交大資工 蔡文能 MoreConcepts-24

Accessing Individual Characters

• It’s almost like for a C-string.

string s = “Harry”;

s[0] is ‘H’

s[1] is ‘a’

s[5] is undefined!!!! – no ‘\0’ at the end

Page 25: More Programming Concept

交大資工 蔡文能 MoreConcepts-25

C++ string Operations• = is used to assign a value (char, C-string, or string) to a st

ring.• += is used to append a string, character, or C-string to a str

ing.• + is used to concatenate two strings or a string with somet

hing else• Boolean operations do a dictionary order comparison• << and >> are used for input and output. On input, leading

whitespace is skipped, and the input terminates with whitespace or end of file.

Page 26: More Programming Concept

交大資工 蔡文能 MoreConcepts-26

Other C++ string Operationsswap(a, b); // swap the guts of a with bs.append(s2); // append s2 to ss.c_str( ); // return a C-strings.push_back(c); // append a chars.erase(various); // erases substringss.insert(various); // inserts substringss.clear(); // removes all contentss.resize(cnt); // change the size of s to cnts.replace(various); // replaces characterss.size(); // how many characters?s.length(); // how many characters?s.max_size(); // maximum number of char?s.empty(); // is s empty?s.capacity(); // size without reallocations.reserve(cnt); // reserves memory

Page 27: More Programming Concept

交大資工 蔡文能 MoreConcepts-27

Using c++ string

string s = "Harry ";

s.data() // returns s as a data array, no '\0' .

s.c_str() // returns s as a C-string with '\0'int i = atoi(s.c_str()); // conversion

char *carray = new char[80];

s.copy(carray, 79); // copies up to 79 char

Page 28: More Programming Concept

交大資工 蔡文能 MoreConcepts-28

I/O and File Handling

• Using System call– open, read, write, close

• Using file pointer– FILE * stdin, *stdout, *stderr, *fp;

• Using C++ file object

Page 29: More Programming Concept

交大資工 蔡文能 MoreConcepts-29

C/C++ I/O functions

• C Library 有關 I/O 的宣告在 <stdio.h>

(C++ 有關 I/O 的宣告在 <iostream> )

• printf(char *, …) 是一個函數 (function), 不是特殊 statement !

• scanf(char *, …) 也是 function, 注意要傳變數的 address 給它 !

• 格式很複雜 , 必須小心使用 !

Page 30: More Programming Concept

交大資工 蔡文能 MoreConcepts-30

再談 I/O (1/6)

• Read an integer from keyboard scanf("%d ", &x); /* not good*/

--better approach

static char buf[99]

gets(buf); /* net safe */

x = atol(buf); /* x=atof(buf); */

-- good approach : use fgets( ) instead of gets( )

fgets(buf, sizeof(buf), stdin);

實數用 atof( )

注意 fgets 讀入時尾巴比用 gets 多了 new line

參考 K&R 課本附錄B

Page 31: More Programming Concept

交大資工 蔡文能 MoreConcepts-31

再談 I/O (2/6)

• 讀入多個資料 int m, n; double x, y; char buf[99];fgets(buf, sizeof(buf), stdin);n = sscanf(buf, "%d %f %f ", &m, &x, &y);

• Other useful library functions– strtol, strtod ( 類似 atol, atof )– strtok, strsep ( 切 token 用 )

The strsep( ) function is intended as a replacement for the strtok( ) .

Page 32: More Programming Concept

交大資工 蔡文能 MoreConcepts-32

再談 I/O (3/6)• Use “f”function to open/read/write file FILE * fp;

fp = stdin; /* 從鍵盤 standard input */

fp = fopen("abc.txt", "rt"); /* "rb" for reading binary file */

if(fp==0) { /* error when try to open */ }

fscanf(fp, "format_string", … ); /* fread( ) for binary file */

fp = fopen("abc.txt", "wt"); /* "wb" for writing binary file */

fprintf(fp, … ); /* fwrite( ) for binary file */

sprintf(buf, …); /* write into the char array buf */

fseek( FILE* fp, int offset, int fence);

fclose(FILE* fp);

if( feof(fp) ) { /* end of file */ }

if( ferror(fp) ) { /*...*/ clearerr(fp); } /* file error, clear the error flag! */

See "man fopen" 參考 K&R 課本附錄B

Page 33: More Programming Concept

交大資工 蔡文能 MoreConcepts-33

再談 I/O (4/6) FILE *fopen(const char *path, const char *mode);

''rt'' Open text file for reading. The stream is positioned at the beginning of the file. /* ''rb'' for binary file */ ''r+'' Open for reading and writing. The stream is positioned at the beginning of the file.用 fread 讀 binary file. 用 fwrite 讀 binary. fread/fwrite 讀寫都不轉

換 . ''w'' Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file. ''wb'' for writing binary file. 讀寫不轉換意思是記憶體內外資料相同 ''w+'' Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. ''a'' Open for writing. The file is created if it does not exist. ''a+'' Open for reading and writing. The file is created if it does no exist.

See "man 3 fopen"

Page 34: More Programming Concept

交大資工 蔡文能 MoreConcepts-34

再談 I/O (5/6)

• Use system call to open/read/write file

int hd;hd = open(" abc.txt ", O_RDONLY); /* 0 */

if(hd== -1) { /* error when try to open */ }

n = read(hd, buf, nbytes );

n = write(hd, buf, nbytes);

lseek( int hd, int offset, int fence);

close(hd);

See next slide

See "man 2 open"

參考 K&R 課本附錄B

Page 35: More Programming Concept

交大資工 蔡文能 MoreConcepts-35

#include <fcntl.h> int hd=open("file.ext", flag); O_RDONLY open for reading only O_WRONLY open for writing only O_RDWR open for reading and writing O_NONBLOCK do not block on open O_APPEND append on each write O_CREAT create file if it does not exist O_TRUNC truncate size to 0 O_EXCL error if create and file exists O_SHLOCK atomically obtain a shared lock O_EXLOCK atomically obtain an exclusive lock O_DIRECT eliminate or reduce cache effects O_FSYNC synchronous writes O_NOFOLLOW do not follow symbolic links

flag for

open

System call

再談 I/O (6/6)

See "man 2 open"

Page 36: More Programming Concept

交大資工 蔡文能 MoreConcepts-36

C++ I/O facility

• C++ uses type safe I/O– Each I/O operation is automatically performed i

n a manner sensitive to the data type (operator overloading, actually)– In C, what about this: printf("%d", float_data);

• Standard I/O streams as Objects:– In C: stdin, stdout, stderr (#include<stdio.h>) – In C++: cin, cout, cerr ( #include <iostream>

)

Page 37: More Programming Concept

交大資工 蔡文能 MoreConcepts-37

C++ classes for I/O

Page 38: More Programming Concept

交大資工 蔡文能 MoreConcepts-38

Iostream Library Header Files

– <iostream.h>: Contains cin, cout, cerr, and clog objects

( 新版用 <iostream> )– <iomanip.h>: Contains parameterized stre

am manipulators ( 新版用 <iomanip> )– <fstream.h>: Contains information import

ant to user-controlled file processing operations ( 新版用 <fstream> )

Page 39: More Programming Concept

交大資工 蔡文能 MoreConcepts-39

C++ I/O classes and objects

• ios:– istream and ostream inherit from ios

• iostream inherits from istream and ostream.

• istream: input streams

cin >> someVariable;• cin knows what type of data is to be assigned to someVariable

(based on the type of someVariable).

• ostream: output streams– cout << someVariable;– cerr << “Something wrong: “ << haha << endl;

Page 40: More Programming Concept

交大資工 蔡文能 MoreConcepts-40

Stream Input/Output Classes and Objects (1/2)

• ios:– istream and ostream inherit from ios

• iostream inherits from istream and ostream.

• << (left-shift operator)– Overloaded as stream insertion operator

• >> (right-shift operator) – Overloaded as stream extraction operator

– Both operators used with cin, cout, cerr, clog, and with user-defined stream objects

Page 41: More Programming Concept

交大資工 蔡文能 MoreConcepts-41

Stream Input/Output Classes and Objects (2/2)

• istream: input streamscin >> someVariable;• cin knows what type of data is to be assigned to someVariable (based on the type of someVariable).

• ostream: output streams– cout << someVariable;

• cout knows the type of data to output

– cerr << someString;• Unbuffered - prints someString immediately.

– clog << someString;• Buffered - prints someString as soon as output buffer is full or

flushed

Page 42: More Programming Concept

交大資工 蔡文能 MoreConcepts-42

Stream Output

• ostream: performs formatted and unformatted output– Uses put for characters and write for unformatted

characters

– Output of numbers in decimal, octal and hexadecimal

– Varying precision for floating points

– Formatted text outputs

Page 43: More Programming Concept

交大資工 蔡文能 MoreConcepts-43

Stream-Insertion Operator

• << is overloaded to output built-in types – Can also be used to output user-defined types– cout << ‘\n’;

• Prints newline character

– cout << endl;• endl is a stream manipulator that issues a newline character

and flushes the output buffer

– cout << flush;• flush flushes the output buffer

Page 44: More Programming Concept

交大資工 蔡文能 MoreConcepts-44

Stream Input

• >> (stream-extraction) – Used to perform stream input

– Normally ignores whitespaces (spaces, tabs, newlines)

– Returns zero (false) when EOF is encountered, otherwise returns reference to the object from which it was invoked (i.e. cin)

• This enables cascaded input

cin >> x >> y;

• >> controls the state bits of the stream– failbit set if wrong type of data input– badbit set if the operation fails

Page 45: More Programming Concept

交大資工 蔡文能 MoreConcepts-45

C++ I/O class Member Functions

• cin.get(): inputs a character from stream• cin.get( c ): inputs a character from stream and stores it in c• cin.get(array, size);• cin.getline(array, size);• cin.ignore(3388, “\n”);• cin.putback();• int c = cin.peek( );• cout << setprecision(2) << x;• cout.precision(2);• cout << hex << 123 << endl;

Page 46: More Programming Concept

交大資工 蔡文能 MoreConcepts-46

Sample using iostream

#include <iostream>using namespace std;int main(){

cout.precision (4);cout.width(8);cout<<12.358<<endl;cout.fill ('*');cout.width (8);cout<<12.135<<endl;cout<<"HaHa"<<endl;cout.width (12);cout.setf(ios::left);cout<<135.625<<endl;return 0;

}

Page 47: More Programming Concept

交大資工 蔡文能 MoreConcepts-47

Sample using <iomanip>

#include <iostream>#include <iomanip>using namespace std;int main( ){ int n;

cout << "Enter a decimal number: ";cin >> n;cout << n << " in hexadecimal is: "

<< hex << n << '\n‘;cout << dec << n << " in octal is: "

<< oct << n << '\n'<< setbase( 10 ) << n ;

cout << " in decimal is: " << n << endl;return 0;

}

Page 48: More Programming Concept

交大資工 蔡文能 MoreConcepts-48

Using fstream in C++#include <iostream.h>#include <fstream.h>int main(){ ofstream out("myscore.txt");

if(!out){ cout << "Cannot open file myscore.txt.\n"; return 1;}out << "C++ " << 89.5 << endl;out << "English " << 93.5 << endl;out << "Maths " << 87 << endl;out.close();return 0;

}

Page 49: More Programming Concept

交大資工 蔡文能 MoreConcepts-49

Open binary file

static char a[512];• 直接在 宣告 / 定義時給參數 :

ofstream wf(″data.dat″,ios binary);∷wf.write((char *)a, len);

• 宣告 / 定義後再 openofstream wf;wf.open(″data.dat″,ios binary);∷wf.write((char *)a, sizeof a);

Page 50: More Programming Concept

交大資工 蔡文能 MoreConcepts-50

打開方式 說明ios in∷ 打開檔進行讀操作,這種方式可避免刪除現存檔

的內容 ios out∷ 打開檔進行寫操作,這是默認模式ios ate∷ 打開一個已有輸入或輸出檔並查找到檔尾ios app∷ 打開檔以便在檔的尾部添加資料ios nocreate∷ 如果檔不存在,則打開操作失敗ios noreplace∷ 如果設置了 ios ate∷ 或 ios app∷ ,則可打開已有

檔,否則不能打開ios binary∷ 指定檔以二進位方式打開,默認為文本方式ios trunc∷ 如檔存在,將其長度截斷為零並清除原有內容

C++ 檔案打開方式的選項

Page 51: More Programming Concept

交大資工 蔡文能 MoreConcepts-51

Moving File pointer (1/2)

istream& istream seekg(∷ 〈 position 〉 ) ; istream& istream seekg(∷ 〈 offset 〉,〈參照位置〉 ) ; long itream tellg( )∷ ; 其中,〈 position 〉和〈 offset 〉都是 long 型,用 byte

( 位元組 ) 數表示。 〈參照位置〉有如下幾種:

cur=1 相對於當前 file pointer 位置beg=0 相對於串流的開始位置end=2 相對於串流的結尾位置

myfile.seekg(-38, 1);

Page 52: More Programming Concept

交大資工 蔡文能 MoreConcepts-52

Moving File pointer (2/2)

• ostream& ostream::seekp( 〈 position 〉 ) ;• ostream& ostream::seekp( 〈 offset 〉,〈參照位置〉);• long ostream tellp( ) ;

〈參照位置〉有如下幾種:cur=1 相對於當前 file pointer 的位置beg=0 相對於串流的開始位置end=2 相對於串流的結尾位置

Page 53: More Programming Concept

交大資工 蔡文能 MoreConcepts-53

Sample using ofstream (1/2)#include <iostream>#include <fstream>struct TVChannel{ int channelNum; char channelName[38];};void outputLine( ostream &output, const TVChannel &c );int main( ){ ofstream outTV( "tvinfo.dat", ios::ate );

if ( !outTV ) {cerr << "File could not be opened." << endl;

exit( 1 );}cout << "Enter channel number " << "(1 to 100, 0 to end input)\n? ";TVChannel tv;cin >> tv.channelNum;

Page 54: More Programming Concept

交大資工 蔡文能 MoreConcepts-54

Sample using ofstream (2/2)while ( tv.channelNum > 0 && tv.channelNum <= 108 ) {

cout << "Enter Channel Name\n? ";cin >> tv.channelName;outTV.seekp( ( tv.channelNum - 1 ) *

sizeof( TVChannel ) );outTV.write( reinterpret_cast<const char *>( &tv ),

sizeof( TVChannel ) );cout << "Enter channel number\n? ";cin >> tv.channelNum;

}outTV.close( );

}

Page 55: More Programming Concept

交大資工 蔡文能 MoreConcepts-55

再談 function name overloading Function name overloading 不一定在 class 內 ! function name overloading 是指很多個函數都用同一個

名稱 例如 : int m=2, n=3; double x=3.8, y=4.9; swap(m, n); swap(x, y); 顯然以上兩個 swap 應該是不同函數 , 這是由它們的參數不同得知

的 ! 這在 compile time 就可以決定是用哪一個 swap, 此稱之為 static binding ( 靜態繫結 )! 如何做 ? (next slide)

? 何謂 dynamic binding? (next slide)

C++ 允許同名的 function, 但注意參數

Page 56: More Programming Concept

交大資工 蔡文能 MoreConcepts-56

C++ How to …overloading/polymorphism

C++ 到底是用了什麼技術辦到 function name overloading ? 事實上只是用了一個超級簡單的 idea:– C++ 只是把參數的型別納入函數名稱中而已 , Comp

iler 會偷換 function name, 參數的 type 也變成 function_name 的一部份 : ( static binding)

例如 : void swap(int&, int&); 會被譯為 ( 可能 !): __swap_F2RiRi

如何達成 polymorphism ?透過 virtual function dynamic binding p-> draw( ); 譯成去執行 p 指過去之物件內有

個指標指過去的函數表中 draw 的項目位置指過去的那個函數 ! ( 相關指標在 new 出物件時填入 )

Page 57: More Programming Concept

交大資工 蔡文能 MoreConcepts-57

Tips about Dynamic binding

動態繫結是一種被 Compiler 用的技術 , 它也不是 OO 才有的 , C 語言的 Auto 變數 ( 函數中沒有宣告 static 的 Local 變數 ) 就是使用 Dynamic binding; 在執行期 (Run time) 時才安排於堆疊 (Stack) 中 !

C 語言中把函數當作參數傳的技巧也是使用到Dynamic Binding 的技巧 !

Page 58: More Programming Concept

交大資工 蔡文能 MoreConcepts-58

Stack 應用 again

• Infix expression Postfix expression

• Infix expression: 12+(2*3)/5

• Prefix : +12 / * 2 3 5

* + /Postfix: 12 2 3 5

Page 59: More Programming Concept

交大資工 蔡文能 MoreConcepts-59

Stack 應用 again (cont)

• 使用堆疊把 infix postfix– Stack 內放運算符號和左括號

• 使用堆疊計算 postfix 的答案– Stack 內放 value ( 整數或實數 )

Page 60: More Programming Concept

交大資工 蔡文能 MoreConcepts-60

Thank You!Thank You!

謝謝捧場[email protected]

蔡文能