原文链接:http://www.cnblogs.com/xudong-bupt/p/3509567.html
平时在写C++代码的时候不怎么注重const的使用,长久以来就把const的用法忘记了
写一点东西加深下印象
#include<iostream>
using namespace std;
int main(){
int a1=3; ///non-const data
const int a2=a1; ///const data
int * a3 = &a1; ///non-const data,non-const pointer
const int * a4 = &a1; ///const data,non-const pointer
int * const a5 = &a1; ///non-const data,const pointer
int const * const a6 = &a1; ///const data,const pointer
const int * const a7 = &a1; ///const data,const pointer
return 0;
}
感觉const特别反人类的一点就是他出现在*左边的时候修饰的是右边的数据内容,出现在*右边的时候修饰的反而是指针
const修饰成员函数
(1)const修饰的成员函数不能修改任何的成员变量(mutable修饰的变量除外) (静态数据成员也除外)
(2)const成员函数不能调用非const成员函数,因为非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 修饰没有任何价值。所以,对于值传递来说,加const没有太多意义。
所以:
不要把函数int GetInt(void) 写成const int GetInt(void)。
不要把函数A GetA(void) 写成const A GetA(void),其中A 为用户自定义的数据类型。
总结:在编程中要尽可能多的使用const,这样可以获得编译器的帮助,以便写出健壮性的代码。
浙公网安备 33010602011771号