首页 > 编程 > C++ > 正文

C++中的const

2019-11-06 06:25:55
字体:
来源:转载
供稿:网友

C++语言中的const关键字

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];

不同数据类型

Simple data types (int, float, char…)

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.

Pointers and references (int , char )

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不能变

细节题

int main() { char c; char *p = &c; p = "hello"; return 0;}

p不是 const 的,所以 p 指向的地址的内容可以被修改, 而“hello”是 const 的,不可以被修改,会报错.

int main() { const char *p = "hello"; p[0] = 'a'; cout << p; return 0;}

p指向 const 字符串,不可被修改.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选