zoukankan      html  css  js  c++  java
  • const真有点烦

      在C++中const代替#define的操作,当定义一个const时必须附一个值给它:const int size = 100;通常C++编译器不为const创建存储空间,相反它把这个定义保存在符号表里。

      常见const的几种定义区别:

    1. const int a; 或 int const a; a为常量不可更改。
    2. int const* c; 或const int * c; 修饰变量,指针指向的内容(值)不可变。
    3. int* const d; 修饰指针,指针指向的地址不可变。
    4. const int * const d;或int const * const d;指针的地址和内容均不可改变。
    5. 修饰函数参数:
     1 voidconst int i)
     2 {
     3 I++;//错误
     4 }
     5 
     6 //为了是理解更加直观应该在函数内部用const限定,避免调用者混淆。
     7 
     8 voidint ic)
     9 {
    10 const int& I = ic;
    11 I++;//错误
    12 }

      6.返回const值

      对于内建类型来说,返回值是否是一个const,并不重要。例如

     1 int f() 
     2 {
     3 return 1;
     4 }
     5 
     6 const int g()
     7 {
     8 return 1;
     9 }
    10 
    11 int main()
    12 {
    13 const int j = f();
    14 int k = g();
    15 }
    16 
    17 都可以正常运行;

      7.传递和返回地址

     1 void t(int* i) { }
     2 
     3 void u(const int* cip)
     4 {
     5 *cip = 2;//错误,指针指向的内容不可改变。
     6 int i = *cip; //正确
     7 int* ip2 = cip;//错误,Int* ip2没有const限制,
     8 }
     9 
    10 const char* v() 
    11 {
    12  return “result of fun”;
    13 }
    14 
    15 const int* const w() 
    16 { 
    17 sataic int I;
    18  return &I;
    19 }
    20 
    21 int main()
    22 {
    23 int x =0;
    24 int* ip = &x;
    25 const int* cip = &x;
    26 t(ip); //正确
    27 t(cip);//错误,不能被更改
    28 u(ip); //正确
    29 u(cip);//正确
    30 char* cp = v();//错误
    31 const char* cpp = v();//正确
    32 int* ip2 = w();//错误
    33 const int* cip2 = w();//正确
    34 const int* const cip2 = w();//正确
    35 }

      8.类中的const

      为了保证一个类对象为常量,const成员函数只能对于const对象调用。如果声明一个const类型的成员函数,则该成员函数可以被一个const对象所调用。一个没有被明确声明为const的成员函数被看成是将要修改对象中数据成员的函数,且编译器不允许被const对象所调用。定义const类型的成员函数不是const int func();这个只是表示函数的返回值为const,正确的const成员函数为int func() const;这个格式才表示函数为const类型,才能被const对象调用。

     1 class X
     2 
     3 {
     4 int i;
     5 public:
     6 X(int ii);
     7 int func() const;
     8 };
     9 
    10 X::X(int ii) :i(ii) { }
    11 int X::func() const //关键字const必须同样出现在定义里,不然会认为不是一个函数
    12 { 
    13 return I;
    14 }
    15 
    16 int main()
    17 {
    18 X x1(10);
    19 Const X x2(20);
    20 X1.func();
    21 X2.func();
    22 //一个const成员函数可以被const对象和非const对象调用,但是成员函数并不会默认为const
    23 //在使用中,不用于修改对象数据成员的任何函数都应该声明为const成员函数,这样它可以和const对象一起使用。
    24 
    25 }
  • 相关阅读:
    注册表设置开机启动
    Sql Server 行转列、列转行
    [转]JavaScript继承详解
    创建开机启动项快捷方式
    【转】IEnumerable与IEnumerator区别
    [转]winform缩放时,控制控件的比例
    【转】反射调用性能比较
    Unity Ioc 学习笔记1
    【转】深入探析c# Socket
    【转】BOOL和bool的区别
  • 原文地址:https://www.cnblogs.com/fuzhuoxin/p/12121784.html
Copyright © 2011-2022 走看看