c++中的const

来源:互联网 发布:仙侠网络 编辑:程序博客网 时间:2024/06/01 21:19

先吐槽一下,C++你还能更复杂一点吗?尤其是学习了java之后,c++怎么那么事多啊。

1 为什么引入const

  不用const,C++语言完全能够实现所有功能。const 只是增加一个约束条件,帮助程序员增加代码约束。

2 cons t的用法总结:

1)常量: 后面可以加基本类型,对象,指针,引用

2)const 代替#define来定义常量

3)常量函数 getValue() const:  防止误修改了类成员值


3 const容易出问题的地方

1)const引用

      const引用可以指向 const常量,变量,兼容的其他的类型的变量

      non const引用只能指向 变量

      We can use a nonconst object to initializer either a const or nonconst reference. However, initializing aconst reference to a nonconst object requires a conversion, whereas initializing a nonconst parameter is an exact match.

    

        const引用指向不同类型的对象的时候,只能读对象的值,不能写对象的值。写也是改写了临时变量的值,不会改变原始变量的值。

2) 作为函数签名:

       const可以修饰入参,返回值,函数。

       const修饰入参是引用或者指针的时候,可以作为函数签名重载;const入参是值传递的时候,不可以作为函数签名重载;

       const修饰返回值的时候,不能重载

       const函数能重载,是因为编译器把const函数变为 (const T *this, ...)

3)const对象调用函数

       const对象调用函数只能调用const函数

       non const对象既可以调用non const函数,也可以调用const 函数。但是优先调用non const函数。

4)  常量函数返回值也是常量

      getValue()const{return p;}  p是类的成员变量,但是用const函数后,返回值p是常量了。 如果返回一个引用,那么必须用const修饰


    int& getValue()const{return p;} //p 是int型,  错误,必须返回const int &
    const Parent getValue()const{return p;} // p是parent型。 错误,必须返回const Parent &

0 0