const用法

C++ const 允许指定一个语义约束,编译器会强制实施这个约束,允许程序员告诉编译器某值是保持不变的。如果在编程中确实有某个值保持不变,就应该明确使用const,这样可以获得编译器的帮助。

const修饰指针变量时:

  (1)只有一个const,如果const位于*左侧,表示指针所指数据是常量,不能通过解引用修改该数据;指针本身是变量,可以指向其他的内存单元。

  (2)只有一个const,如果const位于*右侧,表示指针本身是常量,不能指向其他内存地址;指针所指的数据可以通过解引用修改。

  (3)两个const,*左右各一个,表示指针和指针所指数据都不能修改。

const修饰函数参数

  传递过来的参数在函数内不可以改变,与上面修饰变量时的性质一样。

void testModifyConst(const int _x) {
     _x=5;   ///编译出错
}

3.const修饰成员函数

(1)const修饰的成员函数不能修改任何的成员变量(mutable修饰的变量除外)

(2)const成员函数不能调用非onst成员函数,因为非const成员函数可以会修改成员变量

 4.const修饰函数返回值

如果返回const data,non-const pointer,返回值也必须赋给const data,non-const pointer。因为指针指向的数据是常量不能修改。

(2)值传递

 如果函数返回值采用“值传递方式”,由于函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。所以,对于值传递来说,加const没有太多意义。

所以:

  不要把函数int GetInt(void) 写成const int GetInt(void)。
  不要把函数A GetA(void) 写成const A GetA(void),其中A 为用户自定义的数据类型。

  在编程中要尽可能多的使用const,这样可以获得编译器的帮助,以便写出健壮性的代码。

#include<iostream>
using namespace std;


/*void funn(const int  a){
  a=12;
};*/

const int *func(){
int b =12;
int *a=&b;

return a;
}


class Test{
public:
int a;
Test(int a){
a=a;
}
/*void show() const{
a=12;
}*/

void show() const{

//change();
}
void change(){
  a=12;
}

};
int main(){
Test t(12);
t.show();
//const int a=12;
int a=13;
a=13;
//funn(a);
//int b = func();
const int *b = func();
return 0;
}

参考:https://www.cnblogs.com/xudong-bupt/p/3509567.html

原文地址:https://www.cnblogs.com/webcyh/p/11318368.html