[C++] 3-1.3 c++ constant pointer type reference

[C++] 3-1.3 c++ constant pointer type reference

1. Constant pointer type

The declaration form is as follows:

int const* p;  //或者是 const int* p;

Constant pointer is also called constant pointer, which can be understood as a constant pointer;
that is, the address pointed to by this pointer is a constant. (The pointer here is just a variable)

Regarding the constant pointer
1.1. The object pointed to cannot be modified by this pointer, but it can still be modified by the original declaration;
1.2. It can be assigned to the address of a variable. The reason why it is called a constant pointer is to restrict the value of the variable through this pointer. ;
1.3. It can also point to other places, because the pointer itself is just a variable and can point to any address;

Examples of constant pointers:

#include <iostream>

int main() 
{
    
    
	int a{
    
     77 };//c++11的初始化方式,建议使用这种窄化初始化方式;
	int b{
    
     66 };
	const int* p1 = &a;
	std::cout << "p1=" << p1 << std::endl;
	std::cout << "a=" << a << std::endl;

	a = 300;     //OK,仍然可以通过原来的声明修改值,

	std::cout <<"a="<< a << std::endl;
	//*p1 = 56;  //Error,*p1是const int的,不可修改,即常量指针不可修改其指向地址的值;
	p1 = &b;     //OK,指针还可以指向别处,因为指针只是个变量,可以随意指向;
	
	std::cout <<"p1="<< p1 << std::endl;

	std::cin.get(); //等待从键盘读取字符
	return 0;
}

Run as follows:
Insert picture description here

2. Constant pointer type reference

#include <iostream>

int main()
{
    
    
	const char* a = "jn10010537";    //常量指针变量a为指向"jn10010537"字符串的首地址;
	const char* b = "hello";

	//申明并初始化常量指针类型的引用
	//当一个引用变量一旦绑定另一个变量,引用的关系就不能再改变了。
	const char*& c = b;

	std::cout << "b=" << b << std::endl;
	std::cout << "c=" << c << std::endl;

	c = a; //即把"jn10010537"字符串的首地址 放到 常量指针变量b中;

	std::cout <<"b="<< b << std::endl;
	std::cin.get(); //等待从键盘读取字符
	return 0;
}

Run as follows:
Insert picture description here

3. About error-prone

Error-prone -1
"const char *" type values ​​cannot be used to initialize entities of "char *" type
Insert picture description here
error-prone -2
cannot use "const char *" type values ​​to initialize "char *&" type references (unconstrained )
Insert picture description here

Guess you like

Origin blog.csdn.net/jn10010537/article/details/115288969