3月22日 幾個bother me的小問題

來源:互聯網
上載者:User

太倒黴了,剛打好的就不知怎地被關了,,

首先是typedef ,總是見到,但自己還真就沒咋用過

如果不用typedef

#include <stdio.h>
struct _shit
{
 int A,b;
}shi,*pshi;
void main(void)
{

 struct _shit p;
 struct _shit* p2;
 p2 = &p;
 p2->A = 5;
 printf("%d/n",p2->A );
 shi.A = 1;
 pshi = &shi;
 pshi->b = 2;
 printf("shi's A:%d   b:%d/n",pshi->A ,shi.b ); 
}

shi 和pshi只是一個普通的struct _shit的變數和指標,和mAin()中的p和p2沒有區別,定義struct _shit  的變數和指標的時候也必須用struct _shit  p; sturct _shit* p2;

如果用了typedef的話

#include <stdio.h>
typedef struct _shit
{
 int A,b;
}shi,*pshi;
void main(void)
{
 shi  p;
 pshi p2;
 p2 = &p;
 p2->A = 5;
 printf("%d/n",p2->A );
}
shi 和pshi就變成了struct _shit的類型和其指標類型,因此在定義struct _shit的變數和指標的時候就可以用shi p;和pshi p2;

另外只要是指標,無論指向什麼,都是4位元組;

//--------------------------------------------------------------------------------------------

另外就是c++中的&了,說是地址引用,實際上是比c更墨跡了,,以前用c++的時候都不喜歡用這個,

#include <iostream>

class shit
{
public:
 int A,b;
public:
 int shi(void);
};
int func(shit* s);
int main(void){
 
 shit shi,*dAbiAn;
 dAbiAn = &shi;
 func(dAbiAn);
 shi.shi ();
 printf("%d   %d/n",shi.A,shi.b );
 printf("size %d /n",sizeof(dAbiAn));
 
 return 0;
}
//--------------------------------------------------------------------
int func(shit* s)
{
 s->A = 5;
 return 0;
}
//--------------------------------------------------------------------
int shit::shi (void)
{
 this->b = 3;
 return 0;
}
//--------------------------------------------------------------------

在這個小程式裡很說明問題

如果是int func(shit* s) 那很顯然和 c裡一樣要傳進去個指標類型的,或者把變數取地址func(&shi)這樣引用,

如果是 int func(shit* &s),傳指標類型的同樣沒問題,就當&不存在好了,,他們的彙編出來都是完全一樣的.但由於這兩種形式都是將虛函數s定義成了指標,所以在func函數中要把s當作指標來用,既用->,,

如果是 int func(shit &s),則要傳進來變數或對象func(shi),在函數func裡把形參s當作變數用,s.b  如傳指標也要這樣func(*dAbiAn),

要記住的就是c++的類型強制轉換是很困難的,它的形參是什麼就給它傳什麼就可以了,但在組譯工具來看無論是形參是聲名成指標shit* s  還是shit* &s 還是 shit &s ,都是一樣的,取的s在棧中位移地址

13:       shit shi,*dAbiAn;
14:       dAbiAn = &shi;
00401169 8D 45 F8             lea         eax,[ebp-8]
0040116C 89 45 F4             mov         dword ptr [ebp-0Ch],eax
15:       func(shi);
0040116F 8D 4D F8             lea         ecx,[ebp-8]
00401172 51                   push        ecx
00401173 E8 8D FE FF FF       call        @ILT+0(func) (00401005)
00401178 83 C4 04             add         esp,4

聯繫我們

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