zoukankan      html  css  js  c++  java
  • 条款03 尽可能使用const

    一、概述

    使用const约束对象:可以获得编译器的帮助(指出相关出错的地方)

    const与成员函数:const重载、转型、避免代码重复

    二、细节

    1. 为什么有些函数要返回const对象(看上去没必要)?

    返回const对象:a * b = c;  //operator*()函数返回一个const对象,故该表达式错误

    补充:我们的本意或许是a * b == c,此时返回const是没影响的,故返回const可以预防“没意思的赋值动作”

    2. const成员函数不能避免对象被更改的情况

    mutable成员变量可以更改,即使在const成员函数内

    3. 两个成员函数因const相互重载,而函数体内代码重复

    我们可以令non-const版本调用const版本,来避免代码重复

    class A {
    public:
    	const char &operator[](size_t pos) const
    	{
    		...
    		return text[pos];
    	}
    	char &operator[](size_t pos)
    	{
    		return const_cast<char&>(static_cast<const A&>(*this)[pos]);
    	}
    }; 
    

      

  • 相关阅读:
    Windows 服务程序(一)
    API---注册表编程
    API---文件操作
    main(argc, char *argv[])
    C 自删除技术---批处理方式
    分治法排序
    TDD尝试:nodejs单元测试
    尝试create tech team
    Yum重装走过的坑
    求生欲很强的数据库
  • 原文地址:https://www.cnblogs.com/xzxl/p/7845645.html
Copyright © 2011-2022 走看看