应用题   请使用VC6或使用【答题】菜单打开proj2下的工程proj2,其中定义了Component类、Composite类和Leaf类。Component是抽象基类,Composite和Leaf是Component的公有派生类。请在横线处填写适当的代码并删除横线,以实现上述类定义。此程序的正确输出结果应为:
    Leaf Node
    注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“// ****found****”。
    #include <iostream>
    using namespace std;        class Component {
    public:
    //声明纯虚函数print()
    // **********found**********
    ______
    };        class Composite:public Component {
    public:
    // **********found**********
    void setChild(______)
    {
    m_child = child;
    }
    virtual void print() const
    {
    m_child -> print();
    }
    private:
    Component * m_child;
    };        class Leaf:public Component {
    public:
    virtual void print() const
    {
    // **********found**********
    ______
    }
    };        int main()
    {
    Leaf node;
    Composite comp;
    comp.setChild(&node);
    Component * p = ∁
    p -> print();
    return 0;
    }
 
【正确答案】(1)virtual void print() const=0; (2)Component*child (3)cout << 'Leaf Node' << endl; 答案考生文件夹
【答案解析】[考点] 本题考查抽象类Component类及其派生类Composite和Leaf,其中涉及纯虚函数和成员函数。纯虚函数要根据在派生类中该函数的返回值、参数、有无const来确定。 (1)主要考查考生对纯虚函数的掌握,题目要求声明纯虚函数print()。在其派生类中print()函数的定义为virtual void print() const,由此可知纯虚函数为virtual void print() const=0。 (2)主要考查考生对成员函数的掌握,题目要求填写函数void setChild的形参,由setChild的函数体可知形参为child,再看类的私有成员m_child的定义:Component*m_child;。由此可知形参为:Component*child。 (3)主要考查考生对纯虚函数的掌握,先看主函数的程序: Leaf node; Composite comp; comp.setChild(&node); Component* p = ∁ p->print(); 第一条和第二条语句都是定义语句,第三条语句调用函数setChild,由setChild函数的定义可知,comp中的m_child等于node,第四条语句定义了个指针p指向comp的地址,也就是node,最后一条语句通过指针p调用函数print,也就是调用类Leaf的函数print,因为题目要求输出:Leaf Node,因此在这里添加语句:cout<<'Lear Node'<<endl;。