我有一個名爲Particle的類,它有一個std :: set作爲成員。這個類看起來是這樣的:如何正確封裝std :: set?
class Particle {
private:
std::set<vtkIdType> cells;
std::set<vtkIdType>::iterator ipc;
public:
Particle() {};
enum state {EXISTS = -1, SUCCESS = 0, ERROR = 1};
state addCell(const vtkIdType cell);
int numCells() { return static_cast<int>(cells.size()); }
vtkIdType getFirstCell() { return (*(ipc = this->cells.begin()));}
vtkIdType getNextCell() { return *(++ipc); }
vtkIdType hasNextCell() { ++ipc; if (ipc == this->cells.end()) return false; --ipc; return true; }
std::string getOutput();
};
我很不滿getFirstCell()
,getNextCell()
尤其是hasNextCell()
,他們的存在是因爲我不想暴露自己設定。我不得不使用通過++ipc
和--ipc
的方式,因爲if((ipc+1) == this->cells.end())
給出了一個編譯器錯誤,ipc + 1似乎是問題所在。
什麼是封裝一個集合並訪問它的好方法?另外,有沒有一種很好的方法來擺脫getFirstCell()
函數?
在此先感謝。
編輯:我發佈的代碼只是類結構的一個例子。 「真實」類包含更多的集合和其他數據,這對於這個問題並不重要(我認爲)。
您可以將'hasNextCell'實現爲'iterator i = ipc; return ++ i!= cells.end();'以避免在查詢期間改變狀態。就個人而言,我會與詹姆斯的回答一起,並展示「開始」和「結束」。 – 2009-12-02 18:04:19