const指针与指向const的指针
const指针
int main() {
int num = 42;
int* const p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
num = 76;
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
运行结果: 可以看出,num被成功修改,*p发生了改变,即p指向的那段内存空间的值可以改变,const在这里修饰指针p。
int main() {
int num = 42;
int* const p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
int num2 = 76;
p = &num2;
cout << "num = " << num << endl;
cout << "num2 = " << num2 << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
编译报错: 报错指出,p的指向无法修改,因为const在这里修饰的是指针本身p。
指向const的指针
int main() {
const int num = 10086;
const int* p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
*p = 10088;
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
编译报错: num声明为const,显然不能直接修改,当通过使用指向num的指针p来修改时,也行不通。
int main() {
const int num = 10086;
const int* p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
const int num2 = 10010;
p = &num2;
cout << "num = " << num << endl;
cout << "num2 = " << num2 << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
运行结果: 可以看出,p的指向发生了改变,显然这里的const修饰的是p所指向的内容。
int main() {
const int num = 10086;
int* p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
编译报错: const内容无法赋值给普通的指针,只能赋给用const修饰类型的指针。
指向const的const指针
int main() {
const int num = 100;
const int* const p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
*p = 99;
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
编译报错:
int main() {
const int num = 100;
const int* const p = #
cout << "num = " << num << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
const int num2 = 99;
p = &num2;
cout << "num = " << num << endl;
cout << "num2 = " << num2 << endl;
cout << "p = " << p << endl;
cout << "*p = " << *p << endl << endl;
return 0;
}
编译报错:
- 总结:
const 在 * 之后时修饰的是指针本身,表示指针指向不可变; const 在 * 之前时修饰的是指针所指向的内容,表示这部分值不可变;
|