我有一個類,其中包括一個std :: list,並希望爲const_iterator和private begin()和end()提供公共begin()和end(),只是普通的迭代器。如何使用公共常量迭代器和私有非常量迭代器提供類似stl的容器?
但是,編譯器看到私有版本並抱怨它是私有的,而不是使用公共const版本。
我知道C++不會在返回類型(在本例中是const_iterator和iterator)上重載,因此它選擇了非const版本,因爲我的對象不是const。
在調用begin()或不重載名稱之前將我的對象轉換爲const的缺點begin有沒有辦法實現這一點?
我會認爲這是一種人們已經解決的已知模式,並希望跟隨如何解決這個問題。
class myObject {
public:
void doSomethingConst() const;
};
class myContainer {
public:
typedef std::list<myObject>::const_iterator const_iterator;
private:
typedef std::list<myObject>::iterator iterator;
public:
const_iterator begin() const { return _data.begin(); }
const_iterator end() const { return _data.end(); }
void reorder();
private:
iterator begin() { return _data.begin(); }
iterator end() { return _data.end(); }
private:
std::list<myObject> _data;
};
void myFunction(myContainer &container) {
myContainer::const_iterator itr = container.begin();
myContainer::const_iterator endItr = container.end();
for (; itr != endItr; ++itr) {
const myObject &item = *itr;
item.doSomethingConst();
}
container.reorder(); // Do something non-const on container itself.
}
從編譯器中的錯誤是這樣的:
../../src/example.h:447: error: `std::_List_iterator<myObject> myContainer::begin()' is private
caller.cpp:2393: error: within this context
../../src/example.h:450: error: `std::_List_iterator<myObject> myContainer::end()' is private
caller.cpp:2394: error: within this context
感謝。
- 威廉
據我看到有在你的代碼沒有繼承,也許你應該糾正「我私下派生一個類」。 – 2010-03-13 19:29:54
糟糕,編輯已經得到了同步的,感謝您指出了這一點,現在是糾正。 – WilliamKF 2010-03-13 19:32:18
如果非const的開始和結束僅對您的容器,你爲什麼要爲他們提供私人的功能呢?爲什麼不直接使用列表迭代器。 – AraK 2010-03-13 19:43:40