近期筆試題回顧

來源:互聯網
上載者:User

 1 const 與 const函數重載

  #include <iostream><br />using namespace std;<br />class a<br />{<br />public:<br /> virtual int foo(int *const index)<br /> {<br /> cout<<"2/n";<br /> return 0;<br /> }<br /> virtual int foo(int *index)const<br /> {<br /> cout<<"1/n";<br /> return 0;<br /> }<br />protected:<br /> int value;<br />};<br />class b:public a<br />{<br />public:<br /> int foo(int *const index)<br /> {<br /> cout<<"22/n";<br /> return 0;<br /> }</p><p> int foo(int *index)const<br /> {<br /> cout<<"11/n";<br /> return 0;<br /> }<br />};<br />int main()<br />{<br /> b ta;<br /> a* p=&ta;<br /> int index=3;<br /> p->foo(&index);<br /> const int index1=4;<br /> p->foo(const_cast<int*>(&index1));<br />}

輸出結果為22 22。

const函數只能被const對象調用。

 

2 strcpy函數調用

 

3 sizeof()的秘密

#include <stdio.h><br />#include <stdlib.h><br />#define ENUM(a) (sizeof(a) /sizeof( a[0] ))<br />int main()<br />{<br /> char array[] = {'e', 'm','c'};<br /> int d;<br /> printf("ENUM=%d/n",ENUM(array));<br /> printf("%d/n",-1<ENUM(array));<br /> for(d=-1;d<=(ENUM(array))-2; d++)<br /> {<br /> printf("%d",array[d+1]);<br /> }<br /> system("pause");<br /> return 0 ;<br />}

結果輸入ENMU=3,而並不會輸出數組,就是說for的條件並不成立,沒有迴圈。

原因在於sizeof返回無符整數,在比較-1<(unsigned)3時,-1被轉換為無符號數,結果變成一個很大的整數,導致迴圈條件為假。

因此這道題與其說是sizeof()的問題不如說是unsigned的類型轉換問題。

 

void testsizeof(void)<br />{<br /> int x=1, y=0;<br /> y = sizeof(x++);<br /> printf("x= %d, y = %d/n",x,y);<br />} </p><p>

結果輸出為1 4,為什麼呢?因為sizeof()內並不求值,只用式子的類型代入。

 

int main()<br />{<br /> printf("%s,",h(f(1,2)));<br /> printf("%s/n",g(f(1,2))); </p><p> return 0;<br />}

結果輸出:12,f(1,2)

 

聯繫我們

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