• 类的const成员函数,是如何改变const对象的?


    我们知道类里面的const的成员函数一般是不允许改变类对象的,但是我们知道const 类型的指针是可以强制类型转出成非const指针的,同样的道理,this指针也可以被强制类型转换

     1 class Y{
     2  int i;
     3 public:
     4    Y();
     5    void f()const;
     6 
     7 };
     8 
     9 Y::Y(){
    10 
    11   i=0;  
    12 }
    13 
    14 void Y::f()const{
    15 
    16    //i++; 此时是错误的,因为此时this的指针类型是const Y* const this
    17    ((Y*) this)->i++;
    18    (const_cast<Y*>(this))->i++;
    19 
    20 }
    21 
    22 int main(){
    23 
    24    const Y yy;
    25    yy.f();
    26 
    27 }

    虽然上述用法可以实现const成员函数改变const对象,但是这种用法是客户端程序员是非常不友好的,因为客户端程序员不知道const成员函数是否可以改变const对象,对客户端程序员在接口处没有任何提示。除非客户端程序员可以看到const成员函数的源代码,否则无法判断const成员函数是否可以改变const对象

    而最好的办法是在类声明里面使用关键字mutable,以指定一个特定的成员函数可以在一个const对象里被改变

     1 class Z{
     2   int i;
     3   mutable int j;//被mutable 修饰,可以在const成员函数里面被改变
     4 public:
     5    Z();
     6    void f()const;
     7 
     8 };
     9 
    10 
    11 Z::Z():i(0),j(0){}
    12 
    13 void Z::f()const{
    14 
    15   //i++; 没有使用mutable修饰,不可以改变
    16   j++;
    17 
    18 }
  • 相关阅读:
    hadoop3.2.0集群搭建的一些坑!
    springboot整合elasticJob实战(纯代码开发三种任务类型用法)以及分片系统,事件追踪详解
    Flask接口返回JSON格式数据自动解析
    Struts2--国际化
    Struts2--标签tag
    Struts2-OGNL
    Struts2--拦截器Interceptor
    Struts2--struts.xml详解
    Spring--事务管理
    Spring--JDBC
  • 原文地址:https://www.cnblogs.com/cplinux/p/5598337.html
Copyright © 2020-2023  润新知