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

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 19:20:15



  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.     
  13.     friend class CTeacher;

  14.     CStudent &init(char *name,int age); //赋值功能
  15.     void add(int age);  //对静态成员变量操作
  16.     void output(); //输出类对象的两个数据成员
  17.   private:
  18.     char name[20];
  19.     static int age;   //静态成员变量 在类中声明
  20. };

  21. int CStudent::age=0;          //在 类外 定义

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

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

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

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

  41. CStudent &CStudent::init(char *name,int age)
  42. {
  43.     strcpy(this->name,name);
  44.     this->age=age;
  45.     return (*this);
  46. }
  47. void CStudent::add(int age)
  48. {
  49.     CStudent::age += 10;
  50. }
  51. void CStudent::output()
  52. {
  53.     cout<<this->name<<" "<<this->age<<endl;
  54. }

  55. /*--------------------------------------------------*/
  56. class CTeacher
  57. {
  58. public:
  59.     CStudent &visit(CStudent &student,char *name,int age);    
  60. };

  61. CStudent &CTeacher::visit(CStudent &student,char *name,int age)
  62. {
  63.     strcpy(student.name,name);
  64.     student.age = age;
  65.     return student;
  66. }
  67. /*--------------------------------------------------*/

  68. int main()
  69. {
  70.     CStudent stu1;
  71.     CTeacher teacher1;
  72.     teacher1.visit(stu1,"tom",23);    
  73.     stu1.add(10);        //静态成员变量age +10
  74.     stu1.output(); //23+10=33

  75.     CStudent stu2; //stu1 stu2 共享静态 age
  76.     stu2.add(15); //33+15=48 共享的成语变量
  77.     stu2.output(); // stu2 的 name 初始化是 空串

  78.     return 0;
  79. }

  1. ywx@yuweixian:~/yu/c++/shiyan1$ ./student2
  2. tom 33
  3.        10    这里name 初始化为 空串
  4. the object is deconstructing...
  5. the object is deconstructing...
  6. ywx@yuweixian:~/yu/c++/shiyan1$






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