C++ 中 const 應用總結
阿新 • • 發佈:2018-11-12
//test const 使用細則 class Game { public: int a; }; void function(const Game& obj) { //obj.a = 1; //×,內容不可變 } void function(const string& s) { string tmp = "test"; //s = tmp; //×,內容不可變 } int _tmain(int argc, _TCHAR* argv[]) { //1. 定義常量(兩種本質相同,都是定義常量) const int a = 100; int const b = 100; //a = 1; //錯誤 //b = 1; //錯誤 //2. 指標(*在const左側則則表示指標不可變, 右側表示內容不可改) char cDataA[100]; char cDataB[100]; char cDataC[100]; char cDataD[100]; char* const pDataA = cDataA; //定義指標常量 //pDataA = cDataB; //×,指標為常量不可以變 pDataA[0] = 'A'; //√,內容可變 const char* pDataB = cDataA; //指標指向內容不可以改變 pDataB = cDataB; //√,指標可變 //pDataB[0] = 'B'; //×,內容不可變 char const *pDataC = cDataC; pDataC = cDataB; //√,指標可變 //pDataC[0] = 'A'; //×,內容不可變 const char* const pDataD = cDataD; //pDataD = cDataB; //×,指標為常量不可以變 //pDataD[0] = 'A'; //×,內容不可變 //3. 函式中使用常量 //void function(const int a); //a為形參,呼叫時會自動拷貝,無意義(注意:僅限於基本型別[int,bool,float]) //void function(const char* p); //p所指內容不可改變,這個經常要用到 //void function(char* const p); //p為形參,呼叫時會自動拷貝,無意義 //void function(const Class& a); //此做法是為了提高效率,實際a為地址,不對原物件進行拷貝傳遞,a中內容不可變 //void function(const Type& a); //此做法是為了提高效率,實際a為地址,不對原物件進行拷貝傳遞,a中內容不可變 //4. 類中使用常量 class ClassA { public: const int a; char* const p; int b; public: ClassA(int x, char* ptr): a(x),p(ptr) //√,初始化序列中可以更改常量值 { //a = x; //×,a的初始化只能在初始化序列中 } int GetAValue() const //函式後邊加const表示此函式不改變類成員變數 { if(a>0) return a; //√,返回成員變數是允許的 return b; //√,返回常量也是可以的 } void SetAValue(int v) const { //a = v; //×,不能改變常量引數 //b = v; //×,函式宣告為const不能改變類中成員變數的值 } void SetBValue(int v) { b = v; } }; const ClassA CA(10,NULL); CA.GetAValue(); //√,常量物件可以呼叫常量物件方法 //CA.SetBValue(1); //×,常量物件不能呼叫非常量(const)函式 const ClassA* pCA = new ClassA(10, NULL); pCA->GetAValue(); //√,常量物件可以呼叫常量物件方法 //pCA->SetBValue(1); //×,常量物件不能呼叫非常量(const)函式 ClassA NA(10, NULL); NA.GetAValue(); //√,非常量物件可以呼叫常量物件方法 NA.SetBValue(1); //√,非常量物件可以呼叫普通物件方法 getchar(); return 0; }