【发布时间】:2010-12-05 17:05:40
【问题描述】:
根据 MSDN:“当跟随成员函数的参数列表时,const 关键字指定该函数不会修改调用它的对象。”
有人可以澄清一下吗?这是否意味着该函数不能修改任何对象的成员?
bool AnalogClockPlugin::isInitialized() const
{
return initialized;
}
【问题讨论】:
根据 MSDN:“当跟随成员函数的参数列表时,const 关键字指定该函数不会修改调用它的对象。”
有人可以澄清一下吗?这是否意味着该函数不能修改任何对象的成员?
bool AnalogClockPlugin::isInitialized() const
{
return initialized;
}
【问题讨论】:
表示该方法不修改成员变量(声明为mutable的成员除外),因此可以在类的常量实例上调用。
class A
{
public:
int foo() { return 42; }
int bar() const { return 42; }
};
void test(const A& a)
{
// Will fail
a.foo();
// Will work
a.bar();
}
【讨论】:
还要注意,虽然成员函数不能修改未标记为可变的成员变量,但如果成员变量是指针,则成员函数可能无法修改指针值(即指针指向的地址) ,但它可以修改指针指向的内容(实际内存区域)。
例如:
class C
{
public:
void member() const
{
p = 0; // This is not allowed; you are modifying the member variable
// This is allowed; the member variable is still the same, but what it points to is different (and can be changed)
*p = 0;
}
private:
int *p;
};
【讨论】:
void member() const const*吗?
编译器不允许 const 成员函数更改 *this 或 to 为此对象调用一个非常量成员函数
【讨论】:
正如@delroth 所回答的,这意味着成员函数不会修改任何成员变量,除了那些声明为可变的变量。你可以看到关于 C++ 中 const 正确性的一个很好的常见问题解答here
【讨论】: