面試過程中,一些面試官對C++一些特殊關(guān)鍵字很關(guān)注;
整理了一些比較有說頭的關(guān)鍵字
用來聲明構(gòu)造函數(shù),被聲明的構(gòu)造函數(shù)為顯示構(gòu)造函數(shù),不能在隱式轉(zhuǎn)換中使用。
C++中一個參數(shù)的構(gòu)造函數(shù)或除第一個參數(shù)外均有默認值的多參構(gòu)造函數(shù),有兩個作用:1、構(gòu)造對象;2、默認且隱式的類型轉(zhuǎn)換操作符。
1 class foo
2 {
3 public:
4 explicit foo( int a )
5 : _member( a )
6 {}
7
8 int _member;
9 };
10
11 int bar( const foo & f )
12 {
13 return f._member;
14 }
15
16 bar( 1 ); // 失敗, explicit禁止int到foo的隱式(implicit)類型轉(zhuǎn)換.
17
18 bar( foo( 1 ) ); // 正確, 顯式調(diào)用explicit構(gòu)造函數(shù).
19
20 bar( static_cast<foo>( 1 ) ); // 正確, 通過static_cast調(diào)用explicit構(gòu)造函數(shù).
21
22 bar( foo( 1.0 ) ); // 正確, 顯式調(diào)用explicit構(gòu)造函數(shù), 參數(shù)自動從浮點轉(zhuǎn)換成整型.
用來聲明一個成員變量,被mutable聲明的成員變量,可以在被const修飾的成員函數(shù)中修改。
mutable不可與const、static同時使用。
1 class foo
2 {
3 public:
4 foo()
5 : _member(0)
6 {}
7
8 void ExChange( int a ) const
9 {
10 _member = a;
11 }
12
13 mutable int _member;
14 }
用以聲明一個變量,被volatile聲明的變量意味著有可能被某些編譯器未知的因素更改,因此編譯器不會對其做任何優(yōu)化操作。
從而可以提供對特殊地址的穩(wěn)定訪問,多用于嵌入式編程中。
1 void foo()
2 {
3 //volatile int nData = 1;
4 int nData = 1;
5
6 int nData_b = nData;
7 printf("nData = %d\n",nData_b);
8
9 // c++嵌入asm參見:http://asm.sourceforge.net/articles/linasm.html
10 asm("movl $2, -4(%ebp)\n\r"); // 修改變量地址內(nèi)容
11
12 int nData_a = nData;
13 printf("nData = %d\n",nData_a);
14 }
15
16 使用volatile輸出:
17 nData = 1
18 nData = 2
19
20 不使用volatile輸出為:
21 nData = 1
22 nData = 1