zoukankan      html  css  js  c++  java
  • [导入]const限制符

    1. const变量:const type v; 必须定义时初始化,不能修改其值。备注:关于const变量的作用域要特别注意,它是局部的,而默认的C++变量是全局的。通过加extern限制可以令const对象可以在全局被访问。如代码:(顺便提一下static)

    file1.cpp   type v1;

            const type v2;  //now,v2 is a local variable.

            extern const type v3;//now,v3 is a global variable. must add 'extern'~.

    file2.cpp   type v1; //  error.redeclaration.

            extern type v1; //ok.

            type v2; //ok.but not equivalent to v2 in file1.cpp

            const type v3;  // ok.but not equivalent to v3 in file1.cpp

            extern const type v3; //ok.equal to v3 in file1.cpp. 

    2. const引用:const type& v;是指向const对象的引用。非const引用只能绑定到与该引用同类型的对象。而const引用则可以绑定到不同但相关的类型那个的对象和右值。

    double dv = 1.0;  const int &iv = dv; 编译时等价于

    int temp = dv;  const int &iv = temp; //可以看出对iv的修改并不会影响dv的值

    3.const与指针:(1) 指向const对象的指针: const type* v; 有时记作type const* v;可以修改指针,但不能直接通过该指针修改指针指向的对象。(可以通过定义非const指针指向该对象,从而修改其值)(2)const指针: type *const v;可以修改指针指向的对象,但不能修改指针本身。(3)指向const对象的const指针const type *const v;备注:typedef string * name;  const name v; //v的类型是指向string类型的const指针。) 

    4.const与一般函数: (1) const type1 func(type2 v); 函数返回值为const; (2) type1 func(const type2 v);形参为const变量。因为形参不是引用,不修改实参的值,所以此时的const不起特别的作用;(3)type1 func(const type& v);形参为const引用,不修改传递到形参的实参值。 指针时相同,不修改指针指向的对象的值。

    5.const与类成员函数(常量成员函数):type func(type v) const;等价于type func(const *this,type v) const; 它是值this指针是指向const对象的指针,这个函数不改变调用该函数的对象。(备注:事实上是不可以显示使用this指针作为形参的,但可以在函数体中显示地使用this指针。)

    6.const与迭代器:vector<type>::const_iterator it;  const vector<type>::iterator iter;it指向的元素不能修改,iter指向的元素可以修改,但迭代器本身不能修改。

    7.const与容器: const vector<type> vec; 需要注意此时定义的容器迭代器必须是const_iterator型。
    文章来源:http://liyuxia-life.spaces.live.com/Blog/cns!DA1B364675ACF35!243.entry



    幸运草 2009-02-28 21:38 发表评论
  • 相关阅读:
    TensorFlow进阶(六)---模型保存与恢复、自定义命令行参数
    TensorFlow进阶(五)---图与会话
    TensorFlow进阶(四)---名称域和共享变量
    spark中数据倾斜解决方案
    Hive窗口函数之LAG、LEAD、FIRST_VALUE、LAST_VALUE的用法
    java.lang.RuntimeException: HRegionServer Aborted
    hive中的优化问题
    读取hbase数据到mysql
    用mapreduce读取hdfs数据到hbase上
    centos7下安装elasticSearch错误总结(单节点模式)
  • 原文地址:https://www.cnblogs.com/liyuxia713/p/2540811.html
Copyright © 2011-2022 走看看