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]);
    	}
    }; 
    

      

  • 相关阅读:
    .net 自带的两个内置委托
    Socket
    SQL EXISTS与IN的区别(2)
    一个选择题,写了一个类
    SQL Server- 存储过程(2)
    VS插件-JSEnhancements
    SQL Server- 存储过程(1)
    MVC-工作原理
    C#-属性
    SQL Server 中游标的使用
  • 原文地址:https://www.cnblogs.com/xzxl/p/7845645.html
Copyright © 2011-2022 走看看