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

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-04-19 10:31:53

                 this 指针

this 指针:

1. 只能用在类的成员函数中,它指向调用这个函数的对象

2. 区别形参和数据成员

3. 返回对象本身

4. 静态成员函数没有this 指针




在上一章节中,我们显示的使用写出了 

1. 只能用在类的成员函数中,它指向调用这个函数对象
  1. CStudent input(CStudent *this,char *name,int socre)
  2. {
  3.   this->name=name;
  4.   this->score=score;
  5.   return (*this);
  6. }

  1. void main()
  2. {
  3.   CStudnet stu1;
  4.   stu1.input(&stu1,"tom",89);
  5.   stu1.output();
  6. }
在上面中,this 指针指向了 stu1  这个对象



2. 区别 形参数据成员

在前面,左值和右值一样,使用this区别
 
 通过加 this ,标记了对象指针,和 形参区别了
  1. CStudent input(CStudent *this,char *name,int socre)
  2. {
  3.   this->name=name;
  4.   this->score=score;
  5.   return (*this);
  6. }


3. 返回对象本身

  1. CStudent input(CStudent *this,char *name,int socre)
  2. {
  3.   this->name=name;
  4.   this->score=score;
  5.   return (*this);   返回stu1 对象达到修改数据成员的目的
  6. }



4. 静态成员函数没有this 指针

  类不是一个对象,this是指向一个对象的




this 使用方式:


1. 显示

    比如:当形参和数据成员名字相同时

    比如:返回当前对象本身时

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


  

2. 隐式


   比如:形参和数据成员名字不同时

  1. CStudent input(char *name,int socre名字不同,编译器知道 区别 形参和 数据成员
  2. {
  3.   m_name=name;
  4.   m_score=score;
  5.   return(this);
  6. }

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