曲径通幽论坛

标题: const 成员函数与 mutable [打印本页]

作者: beyes    时间: 2011-12-10 16:10
标题: const 成员函数与 mutable
当类的成员函数被声明为 const 时它就不能修改调用它的对象,也使得函数的隐式参数 this 将被作为 const 类型指针。

const 对象不能调用非 const 成员函数,但 const 对象和非 const 对象都可以调用 const 成员函数。

将一个成员函数声明为 const ,可以按照下面的形式:
[C++] 纯文本查看 复制代码
class X {
  int myvar;
public:
  int f1() const;    // const 成员函数
};

讲一个成员函数声明为 const 的目的是防止函数修改调用它的对象。如下面的代码不能编译通过:
[C++] 纯文本查看 复制代码


class Demo {
    int i;
public:
    int geti() const {
        return i;    //正确
    }
    void seti(int x) const {
        i = x;    //错误,不可以
    }
};


但是有时我们可能希望在 const 函数中修改类的某些成员,但又不想让函数修改类的其它成员,那么可以通过关键字 mutable 来实现。mutable 将覆盖 const 属性,也就是说在 const 成员函数里可以修改 mutable 成员,比如:
[C++] 纯文本查看 复制代码
class Demo {
    mutable int i;
    int j;
public:
    int geti() const {
        return i;    //正确
    }
    void seti(int x) const {
        i = x;    //正确
    }


    void setj(int x) const {
        j = x;    //仍然错误
    }
};

上面程序中,成员变量 i 被定义为 mutable,所以函数 seti() 可以对其修改,但变量 j 并不是 mutable,所以 setj() 不能对其修改。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2