C primer plus 學習筆記(第七章)

2021-09-09 05:42:38 字數 2713 閱讀 6550

第七章 函式—c++的程式設計模組

7.3.5 指標和const

前提**:

int grop=16;

int chips=12;

const int *p_snack=&gorp;

const會鎖定後面乙個符號,所以,此時

p_snack=&chips;    //allowed

*p_snack=20; //error

前提**:

int grop=16;

int chips=12;

int* const p_snack=&grop;

此時有:

*p_snack=20;   //right code

p_snack=&gorp; //wrong code

指標的使用:

#includeconst int arsize=8;

int sum_array(const int * begin,const int * end);

int main()

; int sum=sum_array(cookies,cookies+3);

return 0;

}int sum_array(const int* begin,const int * end)

return total;

}

7.4 函式和二維陣列

為編寫將陣列作為引數的函式,必須牢記,陣列名被視為其位址。

7.6.3 傳遞結構的位址

使用指向結構的的指標來傳遞結構,相比於直接傳遞結構,有以下三個地方需要修改:

呼叫函式時,將結構的位址(&pplace)而不是結構本身(pplace)傳遞給它;

將形參宣告為指向polar的指標,即polar*型別,因此使用了const修飾符

由於形參是指標而不是結構,因此應使用間接成員(->),而不是成員運算子(.)

// strctptr.cpp -- functions with pointer to structure arguments

#include #include // structure templates

struct polar

;struct rect

;// prototypes

void rect_to_polar(const rect * pxy, polar * pda);

void show_polar (const polar * pda);

int main()

cout << "done.\n";

return 0;

}// show polar coordinates, converting angle to degrees

void show_polar (const polar * pda)

// convert rectangular to polar coordinates

void rect_to_polar(const rect * pxy, polar * pda)

7.10 函式指標

與資料項類似,函式也有位址。

假設要涉及乙個名為estimate( )的函式,估算編寫指定行數的**所需的時間。為實現該目標,採用的機制是,將程式設計師要使用的演算法函式的位址傳遞給estimate()。為此,必須能夠完成下面的工作:

獲取函式的位址

宣告乙個函式指標

使用函式指標來呼叫函式

1)獲取函式的位址

獲取函式的位址很簡單:只要使用函式名(後面不跟引數)即可

2)宣告函式指標

double pam(int);

double (*pf)(int);

pf=pam //pf now points to the pam() function

(*pf)也是函式,所以pf就是函式指標,是乙個指向函式的指標

3) 使用指標來呼叫函式

double pam(int);

double (*pf)(int);

pf=pam;

double x=pam(4);

double y=(*pf)(5);

/*..............*/

double y=pf(5); //also call pam() using the pointer pf

**演示:

// fun_ptr.cpp -- pointers to functions

#include double betsy(int);

double pam(int);

// second argument is pointer to a type double function that

// takes a type int argument

void estimate(int lines, double (*pf)(int));

int main()

double betsy(int lns)

double pam(int lns)

void estimate(int lines, double (*pf)(int))

c primer plus學習筆記

1.變數名命名規則 重要的 1 有含義 2 只能用字母字元 數字和下劃線 3 第乙個字元不能是數字 4 區分大小寫 5 不能用c 關鍵字 2.整型 1 無符合型別不能表負值 2 char short 16 int short long 32,int 和longlong 64,long c 11 寬度...

C PrimerPlus學習筆記

if語句中判斷恒等,將常量放前,防止由於 寫成 造成的難以查詢的bug。if 0 count 若寫成 0 count 會報錯,count 0 則不會命名空間 using namespace std cout one cout two std cout one std cout two using s...

C Primer Plus學習筆記

1.組合語言是特地的cpu設計所採用的一組內部指令的助記符,不同的cpu型別使用不同的cpu c給予你更多的自由,也讓你承擔更多的風險 自由的代價是永遠的警惕 2.目標 檔案 可執行檔案和庫 3.可以用畫幾個盒子的方式來跟蹤乙個程式的變數 一門語言的語法就是一套規則,用於管理這種語言中的合法語句組織...