zoukankan      html  css  js  c++  java
  • C++中的const和mutable

     1 #include<iostream>
     2 using namespace std;
     3 //如果在类A的成员函数dis()中想要修改_z,但是不能修改_x,_y怎么办?
     4 //如果dis不加const,那么_x和_y就可以修改,如果加了const,那么_z便不能够修改。
     5 //解决方法就是在_z前面加上mutable,表示这个_z对于类A而言,修改他的值并没有多大影响。
     6 class A
     7 {
     8 public:
     9 A(int x, int y):_x(x),_y(y) {}
    10 void dis() const 
    11 {
    12 cout << "_x=" << _x << endl;
    13 cout << "_y=" << _y << endl;
    14 _z = 3;
    15 }
    16 void foo()
    17 {
    18 cout << "void foo()" << endl;
    19 }
    20 private:
    21 int _x;
    22 int _y;
    23 mutable int _z;
    24 };
    25 
    26 
    27 int main(int argc, char* argv[])
    28 {
    29 
    30 A a(1,2);
    31 a.dis();
    32 a.foo();
    33 
    34 const A b(1,2);
    35 b.dis();
    36 
    37 return 0;
    38 }
    39 
    40  
  • 相关阅读:
    分类模型之支持向量机
    数据预处理
    数据挖掘基本流程
    【项目】项目95
    【项目】项目94
    【项目】项目93
    【项目】项目92
    【项目】项目91
    【项目】项目90
    【项目】项目89
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/15426211.html
Copyright © 2011-2022 走看看