如果你希望编译执行这一点,那么宣布该成员函数const
:
bool contains(string word) const
{
...
}
甲const
功能不允许莫不同的是它的成员变量,并且只能调用其他const
成员函数(它自己或成员变量的成员函数)。
此规则的例外是成员变量声明为mutable
。 [但不应将mutable
用作通用const
解决方法;它才真正意味着当物件的情况的“观察的”状态应该是const
,但内部实现(如引用计数或懒惰的评价)仍然需要改变。]也
注意const
不通过例如传播指针。
因此,在总结:
class Thingy
{
public:
void apple() const;
void banana();
};
class Blah
{
private:
Thingy t;
int *p;
mutable int a;
public:
Blah() { p = new int; *p = 5; }
~Blah() { delete p; }
void bar() const {}
void baz() {}
void foo() const
{
p = new int; // INVALID: p is const in this context
*p = 10; // VALID: *p isn't const
baz(); // INVALID: baz() is not declared const
bar(); // VALID: bar() is declared const
t.banana(); // INVALID: Thingy::banana() is not declared const
t.apple(); // VALID: Thingy::apple() is declared const
a = 42; // VALID: a is declared mutable
}
};
+1为指针的东西,因为'const'只适用于顶层(即不能改变指针本身,只能指向对象)。 – Xeo 2011-06-02 10:36:49
像Xeo说非常酷的示例与ponters ... + 1 ofc :) – NoSenseEtAl 2011-06-02 10:44:14
其实你应该提到关于可变关键字 – 2011-06-02 10:52:03