我有3個班,2個來自其他繼承像這樣:遍歷多個列表連續(C++)
class A {
public:
virtual void foo() {cout << "I am A!" << endl;}
};
class B : public A {
public:
void foo() {cout << "B pretending to be A." << endl}
void onlyBFoo() {cout << "I am B!" << endl}
};
class C : public A {
public:
void foo() {cout << "C pretending to be A." << endl}
void onlyCFoo() {cout << "I am C!" << endl}
};
我想要做的是這樣的:
list<A*> list_of_A;
list<B*> list_of_B;
list<C*> list_of_C;
//put three of each class in their respective list
cout << "First loop:" << endl;
for (list<B>::iterator it = list_of_B.begin(); it != list_of_B.end(); ++it) {
(*it)->onlyBFoo();
}
cout << "Second loop:" << endl;
for (list<C>::iterator it = list_of_C.begin(); it != list_of_C.end(); ++it) {
(*it)->onlyCFoo();
}
//This part I am not sure about
cout << "Third loop:" << endl;
for (Iterate all 3 loops i.e. *it points to As, then Bs then Cs) {
(*it)->foo();
}
爲了輸出:
First loop:
I am B!
I am B!
I am B!
Second loop:
I am C!
I am C!
I am C!
Third loop:
I am A!
I am A!
I am A!
B pretending to be A.
B pretending to be A.
B pretending to be A.
C pretending to be A.
C pretending to be A.
C pretending to be A.
ie ie有時我只想迭代B對象,但有時我想迭代所有的對象。
一個解決辦法是將它們全部存儲在一個列表中,但是我希望能夠通過他們循環型即作爲BS然後再Cs的順序。
另一種建議的解決方案是使用迭代器或iterator_adapters,但我從來沒有使用過,並不能找到一個簡單的例子來幫我開始使用它們。
你要遍歷的A'''B'和在一個循環'C'對象,每個對象上調用不同的功能列表。我理解正確嗎? – wilhelmtell 2010-05-23 00:05:30
您是否知道'it-> foo()'等同於(並優先於)'(* it).foo()'? – 2010-05-23 02:37:39
@wilhelm - 不完全 - 有時我想循環遍歷所有的B和僅調用B的函數,有時我想遍歷所有的As及其子類,並調用從A繼承/覆蓋的函數,即單獨的循環。 我已經重寫了這個問題,以便更清楚我想要什麼。 – 2010-05-24 15:16:40