Wha*_*rld 0 c++ const function
假设我有一个基类foo
class foo {
virtual int get() const = 0;
}
Run Code Online (Sandbox Code Playgroud)
也许有20个子类foo_1,foo_2 ...继承自foo并且形式为:
class foo_1 : public foo {
int get() const { return 1; }
}
...
class foo_20 : public foo {
int get() const { return 20; }
}
Run Code Online (Sandbox Code Playgroud)
突然生活并不那么容易!我有一个类foo_21,必须这样做:
class foo_21 : public foo {
int get() { member_ = false; return 0; }
bool member_;
}
Run Code Online (Sandbox Code Playgroud)
问题是get在基类中声明为const,我必须在子类foo_21中更改一些东西.我怎么能找到一种解决方法呢?
你的基本功能不是virtual,这使得所有这些都具有高度的推测性.你的代码应该已经发布了(尽管可能不像你期望的那样).
你可以使用mutable成员:
class foo_21 : public foo
{
int get() const { member_ = false; return 0; }
mutable bool member_;
};
Run Code Online (Sandbox Code Playgroud)
重要的是,可变变量不会影响类的逻辑常量.如果是的话,你应该重新设计你的设计.
| 归档时间: |
|
| 查看次数: |
1252 次 |
| 最近记录: |