• C++中的const关键字


    一、const引用

    1. 例子一

    #include <iostream>
    using namespace std;
    
    class sp {
    
    public:
        sp() {cout<<"sp()"<<endl;}
        sp(sp *other) {
            cout<<"sp(sp *other)"<<endl;
        }
        /*
         * 此例子中这个拷贝构造函数要么不存在,
         * 只要存在参数必须加const修饰。
         */
        sp(const sp &other) {
            cout<<"sp(sp &other)"<<endl;
        }
        ~sp() {
            cout<<"~sp()"<<endl;
        }
    };
    
    int main(int argc, char **argv)
    {
        sp other = new sp();
        return 0;
    }

    执行结果:

    sp()
    sp(sp *other)
    ~sp()

    1.拷贝构造函数没有使用但是其参数必须是const引用的原因

    sp other = new sp();
    ① new sp()生成一个sp*的临时指针变量。
    ② 然后使用这个临时的sp*为参数调用构造函数sp(sp *other)构造出一个临时的sp对象。
    ③ 使用这个临时的sp对象来调用拷贝构造函数来初始化sp other。
    由于此例中拷贝构造函数的参数传递的是一个sp的临时变量,所有需要是const引用。

    从执行结果上拷贝构造函数的确没有调用,那是高版本的编译器做了优化,但是在编译期编译器仍然做了检查,所以会报这个错!

    2.const引用就不可再拷贝构造函数中修改参数other的成员了(read only), 也不存在这个需求。

    3.另一个例子

    int a = 11;
    int &b = a++;

    编译报错: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ ,修复:

    int a = 11;
    const int &b = a++;

    二、在函数名前后加const

    (1)在函数名后加const:
    只有类的成员函数才能在函数名后面加上const,此时这个成员函数叫做常量成员函数
    常量成员函数在执行期间不能修改对象的成员变量的值(静态成员变量除外),也不能调用同类对象的非常量成员函数(同样的静态成员函数除外)。

    (2)而在函数名前加const则表示函数的返回值为常量。

  • 相关阅读:
    同一账号在不同浏览器不能同时登录
    子页面像父页面传递参数--数组
    bootstaptable动态合并单元格和jxls动态合并单元格
    RedisTemplate的使用
    java项目中读取配置文件
    httpclient调用接口
    drop、truncate和delete的区别
    函数式编程
    常见配置redis.conf介绍
    mysql和redis加入到windows服务
  • 原文地址:https://www.cnblogs.com/hellokitty2/p/10645807.html
Copyright © 2020-2023  润新知