C\C++中函数后面加const

C\C++中函数后面加const

雪山上的小草 2018-12-15 17:53:01  1033  收藏 4

展开

c++ 在函数后加const的意义:
   我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,也就是说,这些函数是"只读"函数,而有一些函数要修改类数据成员的值。如果把不改变数据成员的函数都加上const关键字进行标识,显然,可提高程序的可读性。其实,它还能提高程序的可靠性,已定义成const的成员函数,一旦企图修改数据成员的值,则编译器按错误处理。 const成员函数和const对象 实际上,const成员函数还有另外一项作用,即常量对象相关。对于内置的数据类型,我们可以定义它们的常量,用户自定义的类也一样,可以定义它们的常量对象。
1、非静态成员函数后面加const(加到非成员函数或静态成员后面会产生编译错误)

2、表示成员函数隐含传入的this指针为const指针,决定了在该成员函数中,     任意修改它所在的类的成员的操作都是不允许的(因为隐含了对this指针的const引用);

3、唯一的例外是对于mutable修饰的成员。     加了const的成员函数可以被非const对象和const对象调用     但不加const的成员函数只能被非const对象调用

char getData() const{         return this->letter;

}


c++ 函数前面和后面 使用const 的作用:

  • 前面使用const 表示返回值为const
  • 后面加 const表示函数不可以修改class的成员

请看这两个函数

  • const int getValue();
  • int getValue2() const;1
     
 
  1. /*

  2.  * FunctionConst.h

  3.  */

  4.  
  5. #ifndef FUNCTIONCONST_H_

  6. #define FUNCTIONCONST_H_

  7.  
  8. class FunctionConst {

  9. public:

  10.     int value;

  11.     FunctionConst();

  12.     virtual ~FunctionConst();

  13.     const int getValue();

  14.     int getValue2() const;

  15. };

#endif /* FUNCTIONCONST_H_ */
源文件中的实现1
 

 
  1. /*

  2.  * FunctionConst.cpp 

  3.  */

  4.  
  5. #include "FunctionConst.h"

  6.  
  7. FunctionConst::FunctionConst():value(100) {

  8.     // TODO Auto-generated constructor stub

  9.  
  10. }

  11.  
  12. FunctionConst::~FunctionConst() {

  13.     // TODO Auto-generated destructor stub

  14. }

  15.  
  16. const int FunctionConst::getValue(){

  17.     return value;//返回值是 const, 使用指针时很有用.

  18. }

  19.  
  20. int FunctionConst::getValue2() const{

  21.     //此函数不能修改class FunctionConst的成员函数 value

  22.     value = 15;//错误的, 因为函数后面加 const

  23.     return value;

  24. }

 
  1. #include

  2. using namespace std;

  3. int a=1,b=2;

  4. int *p;

  5. //codeblock c++11

  6. const int* test1()//返回指针常量int const *test1()

  7. {

  8. p=&a;

  9. return p;

  10. }

  11. int* const test2()//返回常量指针

  12. {

  13. p=&a;

  14. return p;

  15. }

  16. int main()

  17. {

  18. int const *t1 = test1();

  19. t1=&b;

  20. cout<<*t1<

  21. int *const t2 = test2();

  22. *t2=3;

  23. cout<<*t2<

  24. return 0;

  25. }

  26.  

指针常量与常量指针的区别:https://blog.csdn.net/m0_37154839/article/details/84864312
--------------------- 
作者:荪荪 
来源:CSDN 
原文:https://blog.csdn.net/smf0504/article/details/52311207 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(C\C++中函数后面加const)