const是一個C和C++語言的關鍵字,意思是宣告一個常數(不能改變的變量),即只讀。const作為類型限定符,是類型的一部分。以下是和C語言兼容的用法:
int m = 1, n = 2; // int 類型的對象const int a = 3; // const int 類型的對象int const b = 4; //同上const int * p //指向 const int 類型對象的指針int const * q; //同上int * const x; //指向 int 類型對象的 const 指針;注意 const 的位置const int * const r; //指向 const int 類型對象的 const 指針int const * const t; //同上const在C++中有更強大的特性。它允許在編譯時確定作為真正的常量表達式。例如,
const int max_len = 42;int a[max_len];For simple non-pointer data types, applying the const qualifier is straightforward. It can go on either side of the type for historical reasons (that is, const char foo = ‘a’; is equivalent to char const foo = ‘a’;). On some implementations, using const on both sides of the type (for instance, const char const) generates a warning but not an error.
For pointer and reference types, the meaning of const is more complicated – either the pointer itself, or the value being pointed to, or both, can be const. Further, the syntax can be confusing. A pointer can be declared as a const pointer to writable value, or a writable pointer to a const value, or const pointer to const value.
A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the value that it points to (called the pointee). Reference variables are thus an alternate syntax for const pointers.
A pointer to a const object, on the other hand, can be reassigned to point to another memory location (which should be an object of the same type or of a convertible type), but it cannot be used to modify the memory that it is pointing to.
A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object. The following code illustrates these subtleties:
void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const constPtrToConst ){ *ptr = 0; // OK: modifies the "pointee" data ptr = NULL; // OK: modifies the pointer *ptrToConst = 0; // Error! Cannot modify the "pointee" data ptrToConst = NULL; // OK: modifies the pointer *constPtr = 0; // OK: modifies the "pointee" data constPtr = NULL; // Error! Cannot modify the pointer *constPtrToConst = 0; // Error! Cannot modify the "pointee" data constPtrToConst = NULL; // Error! Cannot modify the pointer}總結下, const 后面的不能變 例如 int const * ptrToConst, *ptrToConst不能變(不能改變pointee的值)但是ptrToConst能變(能改變pointor指向的對象) int * const constPtr, constPtr不能變但是 *constPtr不能變
p不是 const 的,所以 p 指向的地址的內容可以被修改, 而“hello”是 const 的,不可以被修改,會報錯.
int main() { const char *p = "hello"; p[0] = 'a'; cout << p; return 0;}p指向 const 字符串,不可被修改.
新聞熱點
疑難解答
圖片精選