星期四, 5月 29, 2008

C++ programming language constant type

可以宣告一個data type為constant


const int bufSize = 512;


但是不能宣告一個沒有初始值的const data type,這很合理,因為宣告後就不能再改了。


const int bufSize; //compiler error here


那也不能宣告一個pointer指到const data type, 否則就可以經由pointer 修改constant data type.


const int minSalary; // 什麼都漲,只有薪水是固定的
int * pSalary = &minSalary; // error here.
*pSalary+=100000; // 如果可以的話多好


但是可以宣告一個const pointer type指向data, pointer的值本身可變動,也就是可以指向任何data value,但是你無法經由這個pointer去改變指向的data value, 因為pointer本身是constant type的。


const int * pConstInt; // pointer is constant
pConstInt = minSalary; // OK, can point to a constant value
int maxSalary; // this is not a constant value
pConstInt = &maxSalary; // OK too, can be point to a non-constant value.
*pConstInt += 5000; // 哈哈,不要妄想。你不能從這個pointer去改值。


利用這個特性,const pointer data type所指向的東西無法經由pointer修改。這在C++這種基本上所有的function call都是call by value的方式很好用。有時想要傳一整個structure, 但是又不想函式更改structure裡的內容,這時就可以將pointer 加以const 宣告。


func(const largestruct * pVeryLargeStructure) {
... do something you want here...
... 10000 lines of code below,
... but the sturcture pointed by VeryLargeStructure will not be changed.
}

你可以宣告一個const pointer,pointer本身值不能改變,但是指向的data type可以被改變,我沒有想到什麼時候會用到這樣的特性來解決問題。


int * const ptrNotChanged = &minSalary;
ptrNotChanged = &maxSalary; // error here.


其實寫程式寫了這幾年,雖然使用const這樣的keyword看起來微不足道,但是確可以減少debug的時間,一但養成良好的習慣,在你一開始定義的函數的同時就知道不可能改變傳進去的參數時,就加上const modifier,不但可以防止自己出錯的機會,對於將來自己或是別人來維護你的程式時,更是有很大的幫助。

1 則留言:

匿名 提到...

不錯.有學到東西