多态对象列表

Liv*_*ing 5 c++ polymorphism stl virtual-functions list

我在下面有一个特定的场景。下面的代码应该打印 B 和 C 类的 'say()' 函数并打印 'B say..' 和 'C say...' 但它没有。任何想法.. 我正在学习多态,所以也有评论在下面的代码行中与它相关的几个问题。

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;
}
Run Code Online (Sandbox Code Playgroud)

Lih*_*ihO 4

您的问题称为切片,您应该检查这个问题:学习 C++:多态性和切片

您应该将此列表声明为指向 s 的指针列表A

list<A*> listOfAs;
Run Code Online (Sandbox Code Playgroud)

然后插入它们aBaC指向它的指针,而不是创建它们指向的对象的副本。将元素插入列表的方式是错误的,您应该使用push_back函数来插入:

B bObj; 
C cObj;
A *aB = &bObj;
A *aC = &cObj;

listOfAs.push_back(aB);
listOfAs.push_back(aC);
Run Code Online (Sandbox Code Playgroud)

那么你的循环可能如下所示:

list<A*>::iterator it;
for (it = listOfAs.begin(); it != listOfAs.end(); it++)
{
    (*it)->say();
}
Run Code Online (Sandbox Code Playgroud)

输出:

B Sayssss....
C Says
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。