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

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 09:46:46

                      this指针


  1. #include<iostream.h>
  2. class CStudent
  3. {
  4. public:
  5.    void input(char *name ,int socre);
  6.    void output();
  7. private:
  8.    char *name;
  9.    int socre;
  10. }


  1. void output()
  2. {
  3.   cout<<name<<" "<<socre<<endl;
  4. }

    1. void input(char * name,int socre)
    2. {
    3.   name=name;
    4.   socre=score;
    5. }
 
  1. void main()
  2. {
  3.     CStudent stu1;
  4.     CStudent stu2;

  5.     stu1.input("tom",89);
  6.     stu2.input("jim",77);
  7. }

当我们通过 stu1.input("tom",89);传递数据时
    1. void input(char * name,int socre)
    2. {
    3.   name=name;     将name=tom传递给name
    4.   socre=score;   将socre=89传递给score
    5. }
我们发现input函数中,name=name,socre=socre,编译器根

本不知道左边的name是不是数据成员,还是认为左边的name

是形参name
所以我们没有成功 实现左边的name是stu1 的

name,
那怎么实现呢??



在 c++ 中,通过使用 this 指针


  1. void input(char *name,int socre)
  2. {
  3.   this->name=name;
  4.   this->score-score;
  5. }
那么this 这个指针是一个指针变量,应该装载stu1 变量地

址值,那么这个地址时什么时候给this 的呢??

其实,在 input中隐式的省去了 CStudent *this


  1.  void input(CStudent *this ,char *name,int socre)
  2.  {
  3.    this->name=name;
  4.    this->score-score;
  5.  }

在main函数中, 其实也隐式的省去了 CStudent,我们显示

的写出


  1. void main()
  2. {
  3.    CStudent stu1;
  4.    CStudent stu2;
  5.    stu1.input(&stu1,"tom",89); 
  6.    stu2.input(&stu2,"jim",77);
  7. }



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