C++指標與引用

來源:互聯網
上載者:User

標籤:

1、指標與引用的區別:(1)非空區別。引用不能指向空值。(2)合法性區別。由於指標可能為空白,所以需要測試它以防止它為空白。(3)可修改區別。引用初始化後不可再被修改。(4)內容區別。指標的內容是記憶體位址,引用只是某塊記憶體的別名。所以指標的大小永遠為4,而引用的大小和原變數相同(char為1,int為4)。***Why is an array of reference not possible?***Unlike pointer variables and other variables, references have no storage of their own. A reference is simply an alias for an object that already exists in memory (allowing you to refer to the object by its memory address). Since they have no storage of their own it is impossible to create an array of references. You can of course create an array of objects, each of which can then be referenced. You can also have several references to the same object. But you cannot store those references because there is nothing to physically store other than the object itself, which is already stored. For the same reason you cannot reference references nor can you point to references. You can only refer and point to objects (or point to NULL of course).

2、指定指標的值(指定地址):

struct struc{    int a;    char b[20];    double ccc;}
(struc*) 0表示把0強制轉化成一個struc結構的首地址。這樣((struc*) 0)->b表示b在struct中的位移。3、指標作為函數參數傳遞記住一點,在函數中對參數作任何改變,都不影響該參數在原程式中的值,所以指標,即地址,在原程式中是不會改變的(只是指標作為參數時,指標所指的指可能在函數中會被修改)。如果你要使地址在原程式中也得到改變(如,在函數中用這個指標去申請記憶體),那麼方法I:傳遞指向指標的指標,如:
void GetMemory(char **p, int num){    *p = (char *) malloc(sizeof(char) *num);}
方法II:將指標作為傳回值返回
char* GetMemory(char **p, int num){    p = (char *) malloc(sizeof(char) *num);    return p;}
4、指標作為傳回值如果這個指標是在函數中新建立的,那麼指標本身是存在棧中的,隨著函數的退出,該指標也被釋放。那麼要想得到正確的結果,可以:方法I:申請全域指標。全域變數是存在記憶體中的全域地區。方法II:申請為static。這樣儲存在靜態儲存空間。如:
const char* strA(){    static char str[] ="hello world";    return str;}
5、函數指標(1)定義函數
int max(int x, int y) {    return x>y?x:y;}
(2)聲明函數
int max(int,int);
(3)聲明函數指標並賦值
int (*p)(int,int) = &max;
注意函數指標必須帶有括弧,否則就變成傳回值為int*的函數了。6、數組指標如:int (*a)[10];同函數指標一樣,數組指標也必須要有括弧,否則就變成元素為int*的數組了因為sizeof(*a)結果為40,所以a++就是向後移動40個位元組。7、指標與控制代碼指標標記某個實體記憶體地址控制代碼指向的空間存放著資料在實體記憶體中的地址。即控制代碼是指向指標的指標。Windows記憶體管理器移動對象在記憶體中的位置後,把對象新的地址告之這個控制代碼地址來儲存。8、指標的強制轉換假設類A和類B中都有f()函數。
A* pa = new A(); B* pb = (B*)pa; //把pa的類型強制轉換為了pb類型,但是pa的地址仍然是指向類A的f()。多態正式利用了這個原理。

C++指標與引用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.