指针与const
- 定义的对象中加上const 关键字, 表达一经初始化就不可修改的特性
- const 对象必须初始化
指针与const | ||
---|---|---|
const char* pc; | 指向常量的指针 | pc 初始化可以指向常量字符串, 内容不可以修改,但是指针指向可以修改 |
char* const cp; | 指向char 的常量指针 | cp 初始化不能指向常量字符串,内容可以修改,但是指针指向不可以修改 |
char const* ccp; | 指向常量const 的指针 | ccp 初始化可以指向常量字符串,内容不可以修改,但是指针指向可以修改 |
const char *const cpc; | 指向常量的常量指针 | cpc 初始化可以指向常量字符串,内容和指针指向都不可以修改 |
char const* ccp = "test";
char temp[] = "test2";// ccp[0] = 'i'; error: assignment of read-only location ‘* ccp’
std::cout << "ccp before change pointer: " << ccp << std::endl;
ccp = temp;
std::cout << "ccp after change pointer: " << ccp << std::endl;
理解指针和const 的小窍门
- 实践:
char temp[] = "test2";const char* c1 = "test";// c1[0] = 'i'; //error: assignment of read-only location ‘* c1’c1 = temp;char const* ccp = "test";// ccp[0] = 'i'; error: assignment of read-only location ‘* ccp’std::cout << "ccp before change pointer: " << ccp << std::endl;ccp = temp;std::cout << "ccp after change pointer: " << ccp << std::endl;// char* const cpc = "test cpc"; //warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]char* const cpc = temp;cpc[0] = 'i';char temp2[] = "test2";// cpc = temp2; // error: assignment of read-only variable ‘cpc’const char *const cp2 = "test";// cp2 = temp; error: assignment of read-only variable ‘cp2’// cp2[2] = 'i'; error: assignment of read-only location ‘*(((const char*)cp2) + 2)’