指针和const以及const_cast

  1. 让指针指向一个常量对象,这样可以防止使用指针来修改所指向的量
  • 将int对象a,转为常量对象,有指针c指向
    #include<iostream>
    using namespace std;
    int main()
    {
    	int a = 3;
    	const int* c = &a;
    	cout << *c << endl;  //print 3
    	a = 4;
    	cout << *c << endl;  //print 4
    	return 0;
    }
    
  • 或者可以直接将指针指向常量对象
    #include<iostream>
    using namespace std;
    int main()
    {
        const int a = 3;
        const int* c = &a;
        cout << *c << endl;
        //a = 4;  //invalid
        return 0;
    }
    
  • “初始化”: 无法从const int *转换为int *
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
    	const int a = 3;
    	int* c = &a;  //invalid
    	cout << *c << endl;
    	return 0;
    }
    
  • 对应c不能修改,但是指针c的地址是可以修改的,修改后,同样的也不能修改c
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
    	int a = 3;
    	int b = 4;
    	const int* c = &a;
    	cout << *c << endl;
    	c = &b;
    	cout << *c << endl;
    	return 0;
    }
    
  • 总结 const int* c = &a,这个const就是不能修改*c
  • 通常使用void show_array(const double a[], int n) 来防止函数里面对传入的a数组进行修改
  1. 将指针本身声明为常量,这样可以防止改变指针指向的位置
  • 这样就没法对指针本身进行修改,但是可以对指针指向的值进行修改
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
    	int a = 3;
    	int b = 4;
    	int* const c = &a;
    	*c = 4;  //valid
    	cout << *c << endl;
    	c = &b; //invalid
    	return 0;
    }
    
  1. 前面两种结合,声明指向const对象的const指针
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
    	int a = 3;
    	int b = 4;
    	const int* const c = &a;
    	cout << *c << endl;
    	//*c = 4; //invalid
    	//c = &b; //invalid
    	return 0;
    }
    
  2. const_cast的使用,有时候需要取消const的作用,如下
    #include<iostream>
    
    using namespace std;
    
    int main()
    {
        int a = 3;
        const int* c = &a;
        cout << *c << endl;
        int* d = const_cast<int*>(c);
        // int* e = c; //invalid
        *d = 5; // can modify pointer c
        cout << *c << endl;
        return 0;
    }
    
posted @ 2022-02-20 17:19  xiecl  阅读(48)  评论(0编辑  收藏  举报