我想知道一个类的成员函数是否应该是const,如果它调用其他修改其数据成员的函数.一个很好的例子是一个公共成员函数,它使用私有成员函数来完成工作.
void Foo::Show() const { // Doesn't directly modify data members in this function
ShowPig(); // One or all of these functions modify data members
ShowCow();
ShowBar();
}
Run Code Online (Sandbox Code Playgroud)
也许不是最好的例子,但你明白了.
编译器不应该允许你这样做.以下示例.
//MS VC 2008
class Foo
{
int m_iBar;
void ThisIsConstFunc() const
{
m_iBar = 9; //error C2166: l-value specifies const object
ThisIsNonConst(); //error C2662: 'Foo::ThisIsNonConst' : cannot convert 'this' pointer from 'const Foo' to 'Foo &'
}
void ThisIsNonConst()
{
m_iBar = 9;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |