辨析以下几种指针p的定义。
int tmp = 5; int *p = &tmp; const int *p = &tmp; int const* p = &tmp; int * const p = &tmp; const int * const p = &tmp; int const * const p = &tmp;
根据文献一,可以采用从右往左读的方式区分。
第一个为普通指针,指向普通int变量;
第二个和第三个相同,都是普通指针,指向const int型变量;
第四个是const指针,指向普通int变量;
第五个和第六个相同,都是const指针,指向const int型变量。
实验代码如下:
1 #include <iostream> 2 3 4 void test1() { 5 int tmp = 5; 6 int *p = &tmp; 7 std::cout << "test1:: p value: " << *p << std::endl; 8 // *p and p are common variables. 9 *p = 10; // ok 10 int tmp1 = 9; 11 p = &tmp1; // ok 12 } 13 14 void test2() { 15 int tmp = 5; 16 const int *p = &tmp; 17 std::cout << "test2:: p value: " << *p << std::endl; 18 // *p is read-only, p is common variable. 19 // *p = 10; // error 20 int tmp1 = 9; 21 p = &tmp1; // ok 22 } 23 24 // same with test2 25 void test3() { 26 int tmp = 5; 27 int const* p = &tmp; 28 std::cout << "test3:: p value: " << *p << std::endl; 29 // *p is read-only, p is common variable. 30 // *p = 10; // error 31 int tmp1 = 9; 32 p = &tmp1; // ok 33 } 34 35 void test4() { 36 int tmp = 5; 37 int * const p = &tmp; 38 std::cout << "test4:: p value: " << *p << std::endl; 39 // p is read-only, *p is common variable. 40 *p = 10; // ok 41 // int tmp1 = 9; 42 // p = &tmp1; // error 43 } 44 45 void test5() { 46 const int tmp = 5; 47 const int * const p = &tmp; 48 std::cout << "test5:: p value: " << *p << std::endl; 49 // p is read-only, *p is also read-only. 50 // *p = 10; // error 51 // int tmp1 = 9; 52 // p = &tmp1; // error 53 } 54 55 56 // same with test5 57 void test6() { 58 const int tmp = 5; 59 int const * const p = &tmp; 60 std::cout << "test6:: p value: " << *p << std::endl; 61 // p is read-only, *p is also read-only. 62 // *p = 10; // error 63 // int tmp1 = 9; 64 // p = &tmp1; // error 65 } 66 67 int main() { 68 std::cout << "Hello, World!" << std::endl; 69 test1(); 70 test2(); 71 test3(); 72 test4(); 73 test5(); 74 test6(); 75 return 0; 76 }
References:
(1) https://www.cnblogs.com/bencai/p/8888760.html