我在下面有一個特定的場景。下面的代碼應該打印B和C類的'say()'函數並打印'B說..'和'C說...'但它不會。任何想法..我正在學習多態,所以也有在下面的代碼行中評論了與它相關的幾個問題。多態對象列表
class A
{
public:
// A() {}
virtual void say() { std::cout << "Said IT ! " << std::endl; }
virtual ~A(); //why virtual destructor ?
};
void methodCall() // does it matters if the inherited class from A is in this method
{
class B : public A{
public:
// virtual ~B(); //significance of virtual destructor in 'child' class
virtual void say() { // does the overrided method also has to be have the keyword 'virtual'
cout << "B Sayssss.... " << endl;
}
};
class C : public A {
public:
//virtual ~C();
virtual void say() { cout << "C Says " << endl; }
};
list<A> listOfAs;
list<A>::iterator it;
# 1st scenario
B bObj;
C cObj;
A *aB = &bObj;
A *aC = &cObj;
# 2nd scenario
// A aA;
// B *Ba = &aA;
// C *Ca = &aA; // I am declaring the objects as in 1st scenario but how about 2nd scenario, is this suppose to work too?
listOfAs.insert(it,*aB);
listOfAs.insert(it,*aC);
for (it=listOfAs.begin(); it!=listOfAs.end(); it++)
{
cout << *it.say() << endl;
}
}
int main()
{
methodCall();
return 0;
}
其實*使用*一個裸指針的容器是一個潘多拉的黃蜂巢,但任何數量的東西都可能出錯... – 2012-02-11 16:32:30
我同意。但在這種情況下,我認爲使用裸指針更合適,以便他更好地理解到底發生了什麼。 – LihO 2012-02-11 16:36:08
在上面的情況下,我不得不照顧列表中的元素,一旦我用它..我必須刪除它或什麼? – LivingThing 2012-02-15 18:52:16