《ConstantPointersandPointerstoConstants常量指針和指針常量》由會(huì)員分享,可在線閱讀,更多相關(guān)《ConstantPointersandPointerstoConstants常量指針和指針常量(10頁(yè)珍藏版)》請(qǐng)?jiān)谘b配圖網(wǎng)上搜索。
1、Constant Pointers tMyn 1 Constant Pointers and Pointers to Constants It is possible to distinguish three situations arising from using const with pointers and the things to which they point: A pointer to a const. Here, whats pointed to cannot be modified, but we can set the pointer to point to somet
2、hing else:const char* pstring= “This text cannot be changed!”; Constant Pointers tMyn 2 #include stdafx.h#include using namespace System;using namespace std;int main(array args) const int integer1=20; const int* pInt= coutVariable integer1 is a constant and cannot be changed. endland its value is no
3、w and always: *pInt.endl; const int integer2=40; pInt= You couldnt store the addressof integer1 in a non-constpointer! Constant Pointers tMyn 3 coutBut it is still possible to set the pointer to point to something else! endlVariable integer2 is a constant and cannot be changed. endland its value is
4、now and always: *pInt.endl; return 0; Constant Pointers tMyn 4 A constant pointer. Here, the address stored in the pointer cant be changed, so a pointer like this can only ever point to the address it is initialized with. However, the contents of that address are not constant and can be changed. Con
5、stant Pointers tMyn 5 #include stdafx.h#include using namespace System;using namespace std;int main(array args) int integer1=20; int* const pInt= coutPointer variable pInt is const, so it can only ever point to variable integer1. endlHowever, the contents of variable integer1 is not const!endl; The
6、pointer pInt can only point to anon-const variable of type int! Constant Pointers tMyn 6 integer1=30; coutThe value of the variable integer1 is this time *pInt.endl; return 0; Constant Pointers tMyn 7 A constant pointer to a constant. Here, both the address stored in the pointer and the thing pointe
7、d to have been declared as constant, so neither can be changed. Constant Pointers tMyn 8 #include stdafx.h#include using namespace System;using namespace std;int main(array args) const int integer1=20; const int* const pInt= coutPointer variable pInt is a constant pointer to a constant, endl so it i
8、s not possible to change what pInt points to.endl Constant Pointers tMyn 9 It is neither possible to change the value at the address it contains.endl The value of the variable integer1 is now and always *pInt.endl; return 0; Constant Pointers tMyn 10 Naturally, this behaviour isnt confined to the int types we have been dealing with so far. This discussion applies to pointers of any type.