我有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