初识C++ 的 this ,引用 的区别

    在说明问题之前,先回顾在C语言中,一个对象怎么调用对象本身里的成员。又回顾到了以前TOM请lucy吃饭的问题:

 一 .this 指针   

  1 #include<stdio.h>
  2 
  3 struct person
  4 {
  5     char* name;
  6     void (*fp)(struct person* t);
  7     char* gf;
  8 
  9 };
 10 
 11 void hello(struct person* t);
 12 
 13 int main()
 14 {
 15     struct person tom;
 16     tom.name = "tom";
 17     tom.gf = "lucy";
 18     tom.fp = hello;
 19     tom.fp(&tom);
 20 
 21     struct person songchengyi;
 22     songchengyi.name = "songchengyi";
 23     songchengyi.gf = "pengpeng";
 24     songchengyi.fp=hello;
 25     hello(&songchengyi);
 26 }
 27 
 28 
 29 
 30 
 31 void hello(struct person* t)
 32 {
 33     printf("%s please %s eat! \n",t->name,t->gf);
 34 }
 35 

    为了方便地请吃饭,我们引用了一个函数指针来指向hello,在C++中,类似于hello的操作叫做方法;

   而结构体struct person叫做类;

   在21行 struct person tom这句叫做实例化一个对象,tom就叫做对象;

   为了方便地调用到类自身里面的参数,我们定义了一个struct person* t,当调用方法时候就可以方便地调用本身的参数;

 

   而在C++中,一个对象的this指针并不是对象本身的一部分,不会影响sizeof(对象)的结果。this作用域是在类内部,当在类的非静态成员函数中访问类的非静态成员的时候,编译器会自动将对象本身的地址作为一个隐含参数传递给函数。也就是说,即使你没有写上this指针,编译器在编译的时候也是加上this的,它作为非静态成员函数的隐含形参,对各成员的访问均通过this进行

    

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 struct person
  6 {
  7     char* name;
  8     char* gf;
  9     void hello();
 10 };
 11 
 12 int main()
 13 {
 14     struct person tom;
 15     tom.name = "tom";
 16     tom.gf = "lucy";
 17     tom.hello();
 18 }
 19 
 20 
 21 void person::hello()
 22 {
 23 
 24     cout<< this->name  << " please " << this->gf <<" eat " << endl;
 25 
 26 }
 27 
 28 
~                 

    

   二 .引用,引用很像C语言中的指针,但是,C++中的引用和C语言的指针却有着明显的区别:

    1,引用是为了指向同一块内存,只是名字不同而已;而指针是一个存放地址的变量;

    2,指针可以不初始化,而引用必须要初始化;

    。。。。(还有,以后补充)

    

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 void hello(int &j);
  6 
  7 int main()
  8 {
  9     int i=5;
 10     int *p = &i;
 11     int &j =i;//引用 j 为 i的地址;
 12 
 13     hello(j);
 14 
 15     cout << " j is"<< j << endl;
 16 }
 17 
 18 
 19 void hello(int &j)
 20 {
 21      j = 30;
 22 
 23 }
 24 
 25 
~            

    引用是C++特有的。

   

    

posted @ 2015-06-04 10:59  慢伴拍的二叉树  阅读(1124)  评论(0编辑  收藏  举报