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

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 13:46:15

实验目的:
  
   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.    
  11.     void init(char *name,int age); //赋值功能
  12.     void output(); //输出类对象的两个数据成员
  13.   private:
  14.     char m_name[20];
  15.     int m_age;
  16. };

  17. CStudent::CStudent() //无参构造函数
  18. {
  19.     strcpy(m_name," ");
  20.     m_age=0;
  21. }

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

  27. void CStudent::init(char *name,int age)
  28. {
  29.     strcpy(m_name,name);
  30.     m_age=age;
  31. }

  32. void CStudent::output()
  33. {
  34.     cout<<m_name<<" "<<m_age<<endl;
  35. }


1.无参 构造函数

  1. int main()
  2. {
  3.     CStudent stu[3]; //创建对象数组,并且 无参构造函数 初始化
  4.     for(int i=0;i<3;i++)
  5.     {
  6.         stu[i].output(); //输出 数据成员
  7.     }

  8.     return 0;
  9. }

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



2.有参,无参 一起初始化

  1. int main()
  2. {
  3.     CStudent stu[3]={CStudent(),CStudent("ALICE",21),CStudent()};
  4.     for(int i=0;i<3;i++)
  5.     {
  6.         stu[i].output(); //输出 数据成员
  7.     }

  8.     return 0;
  9. }

  1. ywx@yuweixian:~/yu/c++/shiyan1$ ./student
  2.        0
  3. ALICE 21
  4.        0
  5. ywx@yuweixian:~/yu/c++/shiyan1$


2.对象指针的使用

  1. int main()
  2. {
  3.     CStudent stu;
  4.     CStudent *p=&stu;
  5.     p->output();
  6.     (*p).output();
  7. }

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

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