Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4274740
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 14:55:01

实验目的:

  1. 掌握动态分配对象的方法

  2. 掌握动态分配对象数组的方法




  1. #include <iostream>
  2. #include <cstring> //在 vc6.0 下 使用#include<string.h>
  3.          //在 g++ 环境 为 cstring

  4. using namespace std;
  5. class CStudent
  6. {
  7.   public:
  8.     CStudent();//构造函数 没有返回值
  9.     CStudent(char *name,int age); //定义一个带参 构造函数
  10.     ~CStudent(); //析构函数,唯一,不能重载

  11.     CStudent &init(char *name,int age); //赋值功能
  12.     void output(); //输出类对象的两个数据成员
  13.   private:
  14.     char name[20];
  15.     int age;
  16. };

  17. CStudent::CStudent() //无参构造函数
  18. {
  19.     strcpy(this->name," ");
  20.     this->age=0;
  21. }

  22. CStudent::CStudent(char *name,int age) //带参 构造函数实现
  23. {
  24.     strcpy(this->name,name);
  25.     this->age=age;
  26. }

  27. CStudent::~CStudent()
  28. {
  29.     cout<<"the object is deconstructing..."<<endl;
  30. }

  31. CStudent &CStudent::init(char *name,int age)
  32. {
  33.     strcpy(this->name,name);
  34.     this->age=age;
  35.     return (*this);
  36. }

  37. void CStudent::output()
  38. {
  39.     cout<<this->name<<" "<<this->age<<endl;
  40. }


下面的程序 不会进行析构,

  1. int main()
  2. {
  3.     CStudent *p= new CStudent; //自动无参构造函数 初始化
  4.     p->output();
  5.     return 0;
  6. }

  1. ywx@yuweixian:~/yu/c++/shiyan1$ ./student1
  2.        0
  3. ywx@yuweixian:~/yu/c++/shiyan1$

我们需要自己 手动 删除

  1. int main()
  2. {
  3.     CStudent *p= new CStudent; //自动无参构造函数 初始化
  4.     p->output();
  5.     delete p;
  6.     return 0;
  7. }

  1. ywx@yuweixian:~/yu/c++/shiyan1$ ./student1
  2.        0
  3. the object is deconstructing...
  4. ywx@yuweixian:~/yu/c++/shiyan1$


动态数组

  1. int main()
  2. {
  3.     CStudent *p= new CStudent; //自动无参构造函数 初始化
  4.     p->output();
  5.     delete p;

  6.     CStudent *q = new CStudent[2];
  7.     q[0].init("alice",22);
  8.     q[1].init("marry",23);
  9.     q[0].output();
  10.     q[1].output();

  11.     delete []q;

  12.     return 0;
  13. }


  1. ywx@yuweixian:~/yu/c++/shiyan1$ ./student1
  2.        0
  3. the object is deconstructing...
  4. alice 22
  5. marry 23
  6. the object is deconstructing...
  7. the object is deconstructing...
  8. ywx@yuweixian:~/yu/c++/shiyan1$




阅读(514) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~