zoukankan      html  css  js  c++  java
  • C++关键字mutable

    Mutable    

    (1)mutable的意思是“可变的,易变的”,跟C++中的const是反义词。

    (2)在C++中,mutable也是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中

    实例说明:

    #include <iostream>
    using namespace std;

    class TestMutable
    {
    public:
    TestMutable(){i=0;}
    int Output() const
    {
    return i++; //error C2166: l-value specifies const object
    }
    private:
    int i;
    };

    int main()
    {
    TestMutable testMutable;
    cout<<testMutable.Output()<<endl;
    return 0;
    }

    显然i++在const修饰的函数里是编译通不过的。

    #include <iostream>
    using namespace std;

    class TestMutable
    {
    public:
    TestMutable(){i=0;}
    int Output() const
    {
    return i++;
    }
    private:
    mutable int i;
    };

    int main()
    {
    TestMutable testMutable;
    cout<<testMutable.Output()<<endl;
    return 0;
    }

    在 int i 前面加上 mutable上面就能编译通过了,马上可以看出关键字mutable的作用了。

  • 相关阅读:
    鼠标滑过,解决ul下 li下a的背景与父级Li不同宽的问题
    php函数
    常用函数之数组函数
    php流程控制
    php运算符
    php常量
    php变量的数据类型
    PHP是什么
    css3新增属性
    html5的常用标签
  • 原文地址:https://www.cnblogs.com/danshui/p/2313647.html
Copyright © 2011-2022 走看看