• Duanxx的C++学习: const指针具体解释


     Const指的是一个编译时的常量。

             keywordconst使得代码能够确定一个变量能否够被改动。

    使用了const后,能够防止对变量或者指针的改动;更重要的是,const的引用能够防止对所引用的对象的改动

     

    一般来说,在C语言中,对于一些常量的定义,我习惯性的使用define,而在C++中则最好改为使用const。

     

    对于嵌入式程序而言,const的使用则是相当的微妙的,被const修饰后,其变量是存放在ROM中的,这一点非常重要。

     

    关于Const的指针的使用,文字讲解没有意义,直接參见以下的代码及凝视:

    #include <iostream>
    // const
    // - a compile time constraint that an object can not be modified
    
    int main()
    {
    	const int i = 1;
    	int a = 0;
    	const int *p1 = &i;		///< data is const ,but pointer is not
    
    	int* const p2 = &a;	    ///< pointer p2 itself is const ,but the data p2 point to is not const
    	//int* const p3 = &i;     ///< illegal , cannot convert from 'const int *' to 'int *const '
    	int const* p4 = p1;      ///< if const is on the left of *,data is const
    						///< if cosnt is on the right of *,pointer is const
    
    	const int* const p5 = &i; ///<the data and the pointer are both const
    
    	return 0;
    }
    


  • 相关阅读:
    UART中RTS、CTS
    Verdi:内存不足
    SV学习之interface
    perl学习之:@_ $_
    perl学习之:package and module
    代码变成可执行程序期间,编译器做了那些事?
    perl学习之:use & require
    perl学习之:use and require
    8位二进制补码表示整数的最小值是什么,最大值是什么
    深入理解计算机系统
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4033215.html
Copyright © 2020-2023  润新知