请打开考生文件夹下的解决方案文件proj2,其中定义了Component类、Composite类和Leaf类。Component是抽象基类,Composite和Leaf是Component的公有派生类。请在横线处填写适当的代码并删除横线,以实现上述类定义。

admin2019-04-24  18

问题 请打开考生文件夹下的解决方案文件proj2,其中定义了Component类、Composite类和Leaf类。Component是抽象基类,Composite和Leaf是Component的公有派生类。请在横线处填写适当的代码并删除横线,以实现上述类定义。此程序的正确输出结果应为:
    Leaf Node
    注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。
#include
using namespace std;
class Component{
public:
//声明纯虚函数print()
//********found********
};
class Composite:public Component{
public:
//********found********
  void setChiid(___________)
  {
    m child=child;
    }
    virtual void print()const
    {
    m chiid->print();
  }
private:
  Component*m_chiid;
  };
  class Leaf:public Component{
  public:
  virtual void print()const
  {
//********found********
  }
};
int main()
{
  Leaf node;
  Composite comp;
  comp.setChiid(&node);
  Component*p=∁
  p->print();
  return 0;
}

选项

答案(1)virtual void print()const=0; (2)Component}chiht (3)cout<<"Leaf Node"<
解析 (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=&comp;
p->print();
    第一条和第二条语句都是定义语句,第三条语句调用函数setChild,由setChild函数的定义可知,comp中的m_child等于node,第四条语句定义了个指针P指向comp的地址,也就是node,最后一条语句通过指针p调用函数print,也就是调用类Leaf的函数print,因为题目要求输出:Leaf Node,因此在这里添加语句:cout<<"Leaf Node"<
转载请注明原文地址:https://jikaoti.com/ti/gYt0FFFM
0

最新回复(0)