(int)a、&a、(int)&a、(int&)a的區別

來源:互聯網
上載者:User

例子見:《程式員面試寶典》5.4

#include <iostream>#include <stdio.h>#include <string.h>#include <conio.h>using namespace std;int main(){float a = 1.0f;cout << sizeof(int) <<endl;   //4cout << sizeof(float) <<endl; //4cout << (int)a << endl;       //1cout << &a << endl;           /*取a的地址十六進位0012FF7C*/cout << (int)&a << endl;      /*(int)&a:把a的地址強制轉換成十進位的整型1245052*/cout << (int&)a << endl;/*(int&)a:將a的引用強制轉換為整型,意思是a所在的記憶體,本來定義的時候為float類型,並初始為1.0f,但現在我要按int類型解釋這段記憶體(也就是說a所在的記憶體位址中的資料本來是按float型儲存表示的,你非要按int型來解釋不可)。1.0f   在記憶體中的儲存為0   011   1111   1   000   0000   0000   0000   0000   0000.把他按整型數解釋為2^29+2^28+2^27+2^26+2^25+2^24+2^23=1065353216(int&)a 相當於    *(int*)&a    *(int*)(&a)    *((int*)&a)*/     cout << boolalpha << ((int)a == (int&)a ) << endl;//輸出false.因為1!=1065353216.float b = 0.0f;cout << (int)b << endl;        //0cout << &b << endl;           /*取b的地址十六進位0012FF78*/cout << (int&)b << endl;     //0cout << boolalpha << ((int)b == (int&)b ) << endl;//   輸出true,因為0==0;/*(int&)a   不經過轉換,直接得到a在記憶體單元(就是地址)的值   (int)a     a在記憶體中的值轉換成int類型       float類型在記憶體中儲存的形式是,符號位 指數 尾數   由754標準:階碼採用增碼(該數補碼的反符號),尾數採用原碼   所以1.0f   在記憶體中的形式為   0011   1111   1000   0000   0000   0000   0000   0000   所以輸出的是   0x3f800000   0   在記憶體中的的儲存形式   0000   0000   0000   0000   0000   0000   0000   0000 */return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.