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

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 15:48:05


  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.     friend CStudent &input(CStudent &stu,char *name,int age);
  13.     
  14.     CStudent &init(char *name,int age); //赋值功能
  15.     void output(); //输出类对象的两个数据成员
  16.   private:
  17.     char name[20];
  18.     int age;
  19. };

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

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

  30. CStudent::CStudent(const CStudent &student)
  31. {
  32.     strcpy(this->name,student.name);
  33.     this->age = student.age;
  34. }

  35. CStudent::~CStudent()
  36. {
  37.     cout<<"the object is deconstructing..."<<endl;
  38. }

  39. CStudent &CStudent::init(char *name,int age)
  40. {
  41.     strcpy(this->name,name);
  42.     this->age=age;
  43.     return (*this);
  44. }

  45. void CStudent::output()
  46. {
  47.     cout<<this->name<<" "<<this->age<<endl;
  48. }

  49. CStudent &input(CStudent &stu,char *name,int age)  这里都是 引用,如果不用 & ,就要进行数据拷贝
  50.       返回一个新的对象,
  51. {
  52.     strcpy(stu.name,name);
  53.     stu.age = age;
  54.     return stu;
  55. }
  56. int main()
  57. {
  58.     CStudent stu1("jim",22);
  59.     stu1.output();
  60.     input(stu1,"marry",21);
  61.     stu1.output();    
  62.     return 0;
  63. }


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







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