您的位置:首页 > 编程语言 > C语言/C++

C++中const的用法:使代码更加健壮

2017-11-23 21:50 405 查看
本文将从三个方面来讨论const带来的代码健壮性:const在变量中的用法,const在函数中的用法,const作为返回值的用法。

const在变量中的用法

代码示例:

int num = 1;
const int a = 1;      //a的值不能被改变
const int *b = #  //b的值不能被改变,这个指针的类型是(const int)const data,not const pointer
int const *c = #  //同上,c的值不能被改变,这个指针的类型是(const int)const data,not const pointer
int *const d = #  //d的地址不能被改变, 这个指针的类型是(const *int)const pointer, not const data
const *int e = #  //同上,e的地址不能被改变, 这个指针的类型是(const *int)const pointer,not const data
int const* const f =# //f的地址和值都不能被改变,这个指针类型是(const *int const) const pointer,const data
const *int const g= # //同上,g的地址和值都不能被改变,这个指针类型是(const *int const) const pointer,const data


当用const修饰的时候,被修饰的变量不能被改变,可以防止编程人员对不需要改变的常量进行更改。

const在函数中的用法

代码示例:

class obj{
public:
obj()=default;
int change_a() const{
a = 5;     //错误,禁止const函数修改成员变量(error: assignment of member ‘obj::a’ in read-only object)
display(); //错误,禁止const函数调用非const成员函数(error: passing ‘const obj’ as ‘this’ argument discards qualifiers)
}
void display(){
std::cout << "HI" << std::endl;
}
//省略析构函数
private:
int a = 1;
int b = 1;
};


用const修饰的函数不能修改任何成员变量,不能调用任何非const成员函数。

const作为函数返回值的用法

返回值

const int func(){
return 5;
}

int main()
{
int i = func();
const int j = func();
}


这里func返回的值本身就是一个暂存在外部存储单元中的一个值,所以用const并没有意义,所以
int i
const int j
都是可以接受这个值的。

返回指针(type const *data)

const int *func(){
int *a =  new int(5);
return a;
}

int main(){
int *a1 = func(); // 错误,a应该是一个常量指针(const data, not const pointer)
const int *a2 = func(); //正确
const *int a3 = func(); //错误, 这里是const pointer,但是值是可以改变的,要至少满足返回值的const条件
const *int const  a4 = func(); //正确,这里时刻const data,满足返回值的类型
return a;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 c语言 c++ const