龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > VC开发 >

在子类中调用父类的带参数的构造函数[图](2)

时间:2009-12-30 15:42来源:未知 作者:admin 点击:
分享到:
例2-14 #include iostream.h class animal { public: animal(int height, int weight) { cout"animal construct"endl; } … }; class fish:public animal { public: fish():animal(400,300) { cout"fish construct

  例2-14

  #include <iostream.h>
  class animal
  {
  public:
    animal(int height, int weight)
    {
      cout<<"animal construct"<<endl;
    }
    …
  };
  class fish:public animal
  {
  public:
    fish():animal(400,300)
    {
      cout<<"fish construct"<<endl;
    }
    …
  };
  void main()
  {
    fish fh;
  }

  注意程序中以粗体显示的代码。在fish类的构造函数后,加一个冒号(:),然后加上父类的带参数的构造函数。这样,在子类的构造函数被调用时,系统就会去调用父类的带参数的构造函数去构造对象。这种初始化方式,还常用来对类中的常量(const)成员进行初始化,如下面的代码所示:

  class point
  {
  public:
     point():x(0),y(0)
  private:
     const int x;
     const int y;
  };

  当然,类中普通的成员变量也可以采取此种方式进行初始化,然而,这就没有必要了。

收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!

热评话题

按钮 内容不能为空!
立刻说两句吧! 查看0条评论
精彩图集

赞助商链接