详谈const的使用

一:const修饰的成员变量(先上代码,看完之后节本能明白后面有总结).

#include <iostream>
using namespace std;

int main()
{
  int x=1;
  const int y=x; //const data
  x=3; //accept
  //y=3; read-only variable 'y'
  cout<<"x=:"<<x<<" "<<"y=:"<<y<<endl; //x=3,y=1

  int k=0;
  int *p1=&x; //non-const data,non-const pointer
  const int *p2=&x; //const data,non-const pointer
  int const *p2_1=&x; //const data,non-const pointer
  *p1=6; //accept
  //*p2=3; read-only location '*p2'
  //*p2_1=3; read-only location '*p2_1'
  //p2=&k; //accept
  //p2_1=&k; //accept
  cout<<"*p1=:"<<*p1<<" "<<"*p2=:"<<*p2<<" "<<"x=:"<<x<<endl; //*p1==6,*p2==6,x==6
  //Important
  //Because p1 points to the address of x,the value *p1 will change to p2 and x
  
  int z=0;
  int *const p3=&x; //non-const data,const pointer
  //p3=&z; read-only variable 'p3',The values of p3 is address
  *p3=z; //accept
  cout<<"*p3=:"<<*p3<<endl;

  int const *const p4=&x; //const data,const pointer
  const int *const p5=&x; //const data,const pointer
  cout<<"*p4=:"<<*p4<<" *p5=:"<<*p5<<endl;
  return 0;
}

const修饰指针变量时:

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

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

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

二:const修饰的函数的参

void Const(const int x) 
{ x=6;   //error }

三:const修饰的类的成员函数

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

2.const修饰的成员函数不能调用任何非const成员函数(因为非const成员函数可能改变成员变量的值,而const成员函数能不改变成员变量的值,两者冲突)

class Const
{
   public :
     Const(int x1):x(x1){}

     void testConst(int x1) const
     {
       //x=x1;
       //错误,在const成员函数中,不能修改任何类成员变量

       //change_x(x1);
       //const成员函数不能调用非onst成员函数,因为非const成员函数可以会修改成员变量
      }

      void change_x(int x1)
      {
        x=x1;
      }
    private:
      int x;
};

四:const修饰的函数的返回值

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

const int *testConstFuction()
{
  int x=2;
  int *a=&x;
  return a;
}

{

  const int *b=testConstFuction();
  cout<<"b="<<b<<endl;
  int b_1= testConstFuction();//error
}

2.引用传递

如果返回const data,non-const reference,返回值是不是const data没关系,但是你本来的意图时const data 所以加上const较好

const int &testConstFuction()
{
  int x=2;
  int &a=x;
  return a;
}

{

  const int &b=testConstFuction();//&加不加都可以
  cout<<"b="<<b<<endl;
  int b_1= testConstFuction();//accept,编译也可以通过。
  cout<<"b_1="<<b_1<<endl;

}

3.值传递

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

所以:

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

建议:在写程序的过程中尽量多的使用const,这样可以增强代码的健壮性。(在纠错的过程中尽量让编译器帮我们检查错误,让我们编程变得轻松点,const就是这个功能)

猜你喜欢

转载自www.cnblogs.com/tianzeng/p/9063438.html