设为首页 加入收藏

TOP

2011年计算机等级考试二级C++辅导笔记:类和堆
2014-10-25 11:30:03 来源: 作者: 【 】 浏览:66
Tags:2011年 计算机 等级考试 二级 辅导 笔记 类和

  一、构造函数和析构函数
  前面的例子已经运用了new和delete来为类对象分配和释放内存。当使用new为类对象分配内存时,编译器首先用new运算符分配内存,然后调用类的构造函数;类似的,当使用delete来释放内存时,编译器会首先调用泪的析构函数,然后再调用delete运算符。
  #include iostream.h
  class Date
  {
  int mo,da,yr;
  public:
  Date() { cout< ~Date() { cout< }
  int main()
  {
  Date* dt = new Date;
  cout< delete dt;
  return 0;
  }
  程序定义了一个有构造函数和析构函数的Date类,这两个函数在执行时会显示一条信息。当new运算符初始化指针dt时,执行了构造函数,当delete运算符释放内存时,又执行了析构函数。
  程序输出如下:
  Date constructor
  Process the date
  Date destructor
  二、堆和类数组
  前面提到,类对象数组的每个元素都要调用构造函数和析构函数。下面的例子给出了一个错误的释放类数组所占用的内存的例子。
  #include iostream.h
  class Date
  {
  int mo, da, yr;
  public:
  Date() { cout< ~Date() { cout< }
  int main()
  {
  Date* dt = new Date[5];
  cout< delete dt; //这儿
  return 0;
  }
  指针dt指向一个有五个元素的数组。按照数组的定义,编译器会让new运算符调用Date类的构造函数五次。但是delete被调用时,并没有明确告诉编译器指针指向的Date对象有几个,所以编译时,只会调用析构函数一次。下面是程序输出;
  Date constructor
  Date constructor
  Date constructor
  Date constructor
  Date constructor
  Process the date
  Date destructor
  为了解决这个问题,C++允许告诉delete运算符,正在删除的那个指针时指向数组的,程序修改如下:
  #include iostream.h
  class Date
  {
  int mo, da, yr;
  public:
  Date() { cout< ~Date() { cout< }
  int main()
  {
  Date* dt = new Date[5];
  cout< delete [] dt; //这儿
  return 0;
  }
  最终输出为:
  Date constructor
  Date constructor
  Date constructor
  Date constructor
  Date constructor
  Process the date
  Date destructor
  Date destructor
  Date destructor
  Date destructor
  Date destructor


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2011年计算机等级考试二级C++辅导.. 下一篇2011年计算机等级考试二级C++辅导..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: