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

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 15:12:49

实验目的:

    掌握拷贝构造函数的实验方法


  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(const CStudent &student);

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

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

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

//拷贝析构函数
  1. CStudent::CStudent(const CStudent &student)
  2. {
  3.     strcpy(this->name,student.name);
  4.     this->age = student.age;
  5. }

  6. CStudent::~CStudent()
  7. {
  8.     cout<<"the object is deconstructing..."<<endl;
  9. }

  10. CStudent &CStudent::init(char *name,int age)  &  引用
  11. {
  12.     strcpy(this->name,name);
  13.     this->age=age;
  14.     return (*this);
  15. }

  16. void CStudent::output()
  17. {
  18.     cout<<this->name<<" "<<this->age<<endl;
  19. }

  20. int main()
  21. {
  22.     CStudent stu1("jim",22);
  23.     CStudent stu2(stu1); //接收的一个引用

  24.     stu1.output();
  25.     stu2.output();
  26.     return 0;
  27. }


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


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