對於給定的函數/代碼塊,是否可以讓一個成員變量僅被認爲是可變的?成員變量的臨時可變性
例如
class Foo() {
int blah;
void bar() const {
blah = 5; // compiler error
}
void mutable_bar() const {
blah = 5; // no compiler error
}
}
注:在這種情況下,我不希望在mutable_bar擺脫常量,因爲邏輯常量將被保留。
同樣的問題,但不同的觀點:我可以以某種方式將可變關鍵字應用於方法而不是變量?
我認爲你可以做'const_cast(this) - > blah = 5;'。你需要什麼? –
Elazar
2013-04-27 19:33:13
@Elazar:如果對象實際上首先聲明爲「const」,則這是UB。 *不要這樣做!* – syam 2013-04-27 19:33:58
@syam在這裏聲明瞭什麼'const',究竟是什麼? – lapk 2013-04-27 19:37:37