今天看视频资料,看到讲解const部分,感觉讲的不够清晰,因此自己吸取了一些他人的精华,并进行代码测试,有了一些收获,方便自己、方便他人。http://www.cnblogs.com/xudong-bupt/p/3509567.html
使用const可以更好的约束代码,增强代码的健壮性,一下将简要分析const的位置与使用。
一、修饰变量、指针
经常见到以下几种形式:
1
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num = 5; //普通的整形变量没有const进行修饰。
const int n1 = num; //用const进行修饰,n1的值无法改变,这是常见的修饰形式
int const n2 = num; //用const进行修饰,n2的值无法改变,该效果与上一条一致。
n1++; //代码报错:不能给常量赋值
n2++; //代码报错:不能给常量赋值
return 0;
}
2
#include <iostream>
using namespace std;
int main()
{
int num = 5; //普通的整形变量没有const进行修饰。
int const *p1 = &num //const限制了值得改变,却没有限制指针的改变
const int *p2 = &num //const限制了值得改变,却没有限制指针的改变该结果与上一条一致
p1++; //ok 指针可以进行改变
p2++; //ok 指针可以进行改变
// *p1 += 10; //报错:不能给常量赋值
// *p2 += 10; //报错:不能给常量赋值
return 0;
}
3
#include <iostream>
using namespace std;
int main()
{
int num = 5; //普通的整形变量没有const进行修饰。
int * const p1 = #//指针无法更改,但是值可以更改
*p1 += 10; //此时值为:15
p1++; //报错:不能给常量赋值
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int num = 5;
const int *const p1 = #
// p1++; //报错:不能给常量赋值
// *p1 += 10; //报错:不能给常量赋值
return 0;
}
总结:
1、当const出现在*左边的时候:
const int *p 与 int const *p 是等价的:都是确保指针指向的值不能改变,但指针可以改变 (指针改变了存储地址,此时取值的值将不再是num值了)
代码验证
#include <iostream>
using namespace std;
int main()
{
int num[] = { 1, 2, 3, 4, 5 };
int const* p1 = num;
cout << *p1 << endl;//相当于num[0];
p1++;
cout << *p1 << endl;//相当于num[1];
return 0;
}
2、int *const p:当const出现在*右边时候,指针无法改变,但值却可以改变。
3、const int *const p与int const *const p等价:无法修改指针、无法修改值。
二、const修饰函数参数
传递过来的参数在函数内不可以改变,与上面修饰变量时的性质一样。
#include <iostream>
using namespace std;
void fun(const int num) {
num = 5;//这里对const修饰的num进行了更改
}
int main()
{
int num = 0;
fun(&num);//编译出错
return 0;
}
三、const修饰成员函数
(引用)
(1)const修饰的成员函数不能修改任何的成员变量(mutable修饰的变量除外)
(2)const成员函数不能调用非onst成员函数,因为非const成员函数可以会修改成员变量
#include <iostream>
using namespace std;
class Point{
public :
Point(int _x):x(_x){}
void testConstFunction(int _x) const{
///错误,在const成员函数中,不能修改任何类成员变量
x=_x;
///错误,const成员函数不能调用非onst成员函数,因为非const成员函数可以会修改成员变量
modify_x(_x);
}
void modify_x(int _x){
x=_x;
}
int x;
};
四、const修饰函数返回值
(引用)
(1)指针传递
如果返回const data,non-const pointer(类似:const int *p或 int const *p ),返回值也必须赋给const data,non-const pointer。因为指针指向的数据是常量不能修改。
const int * mallocA(){ ///const data,non-const pointer
int *a=new int(2);
return a;
}
int main()
{
const int *a = mallocA();
///int *b = mallocA(); ///编译错误
return 0;
}
(2)值传递
如果函数返回值采用“值传递方式”,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。所以,对于值传递来说,加const没有太多意义。
所以:
不要把函数int GetInt(void) 写成const int GetInt(void)。
不要把函数A GetA(void) 写成const A GetA(void),其中A 为用户自定义的数据类型。