辨析以下几种指针p的定义。
int tmp = ;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型变量。
实验代码如下:
#include <iostream> void test1() {
int tmp = ;
int *p = &tmp;
std::cout << "test1:: p value: " << *p << std::endl;
// *p and p are common variables.
*p = ; // ok
int tmp1 = ;
p = &tmp1; // ok
} void test2() {
int tmp = ;
const int *p = &tmp;
std::cout << "test2:: p value: " << *p << std::endl;
// *p is read-only, p is common variable.
// *p = 10; // error
int tmp1 = ;
p = &tmp1; // ok
} // same with test2
void test3() {
int tmp = ;
int const* p = &tmp;
std::cout << "test3:: p value: " << *p << std::endl;
// *p is read-only, p is common variable.
// *p = 10; // error
int tmp1 = ;
p = &tmp1; // ok
} void test4() {
int tmp = ;
int * const p = &tmp;
std::cout << "test4:: p value: " << *p << std::endl;
// p is read-only, *p is common variable.
*p = ; // ok
// int tmp1 = 9;
// p = &tmp1; // error
} void test5() {
const int tmp = ;
const int * const p = &tmp;
std::cout << "test5:: p value: " << *p << std::endl;
// p is read-only, *p is also read-only.
// *p = 10; // error
// int tmp1 = 9;
// p = &tmp1; // error
} // same with test5
void test6() {
const int tmp = ;
int const * const p = &tmp;
std::cout << "test6:: p value: " << *p << std::endl;
// p is read-only, *p is also read-only.
// *p = 10; // error
// int tmp1 = 9;
// p = &tmp1; // error
} int main() {
std::cout << "Hello, World!" << std::endl;
test1();
test2();
test3();
test4();
test5();
test6();
return ;
}
References:
(1) https://www.cnblogs.com/bencai/p/8888760.html