1,修饰变量
2,修饰类成员函数,
1)类成员函数中不能改变成员变量的值
2)类成员函数中不能调用非const的成员函数
如:
#include <iostream> 2 using namespace std; 3 class Point{ 4 public : 5 Point(int _x):x(_x){} 6 7 void testConstFunction(int _x) const{ 8 9 ///错误,在const成员函数中,不能修改任何类成员变量 10 x=_x; 11 12 ///错误,const成员函数不能调用非onst成员函数,因为非const成员函数可以会修改成员变量 13 modify_x(_x); 14 } 15 16 void modify_x(int _x){ 17 x=_x; 18 } 19 20 int x; 21 };
3,const修饰函数返回值
(1)指针传递
如果返回const data,non-const pointer,返回值也必须赋给const data,non-const pointer。因为指针指向的数据是常量不能修改。
1 const int * mallocA(){ ///const data,non-const pointer 2 int *a=new int(2); 3 return a; 4 } 5 6 int main() 7 { 8 const int *a = mallocA(); 9 ///int *b = mallocA(); ///编译错误 10 return 0; 11 }
(2)值传递
如果函数返回值采用“值传递方式”,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。所以,对于值传递来说,加const没有太多意义。
所以:
不要把函数int GetInt(void) 写成const int GetInt(void)。
不要把函数A GetA(void) 写成const A GetA(void),其中A 为用户自定义的数据类型。
本文详细介绍了C++中常量引用的使用规则,特别是类成员函数中对成员变量的访问限制。同时,阐述了如何在函数中返回常量引用,以及不同参数传递方式下对常量引用的处理。通过实例代码,帮助开发者理解常量引用在C++编程中的应用及避免常见陷阱的方法。

2256

被折叠的 条评论
为什么被折叠?



