這是我的問題。我有一個持有對象數組的類(在std :: vector中) 這些對象可以從客戶端代碼中修改,所以我創建了一個私有getter,它返回一個指向我需要修改的對象的指針。公共方法使用此getter來修改數組中的對象。C++ const getters的正確性問題
私有getter也用於其他成員函數,它將數組中的對象的特定值返回給客戶端代碼。我希望這些函數能夠返回const,但是我不能這麼做,因爲我使用了前面提到的非const getter。
我知道我可以做一個其他的const getter,但那隻會重複代碼。
如何正確實施?
代碼示例:
class Object;
class Inventory
{
Object* GetObject(int id);
void AddObjectProp(int id, int amount) {
Object* x = GetObject id);
x->prop += amount;
}
//using const here is not posible because GetObject is not const
int GetObjectProp(int id) {
Object* x = GetObject id);
return x->prop;
}
}
謝謝。
是不是http:// stackoverflow。com/questions/123758/how-do-i-remove-code-duplication-between-similar-const-and-non-const-member-func?rq = 1解決同一個問題? – anumi
const的正確性似乎總是要求你重複你的getters(至少返回指針或引用的那些)。由於重複是不正確的,所以必須去做:或者那些討厭的getter,或者const正確性... –