一点琐碎的指针和引用

看薛老师视频,看对象存储内容,有下面代码

grand obj;

grand *ptr_g = &obj;

int *ptr = (int*)ptr_g;

这里为什么用了2个指针?

  因为第一个ptr_g是指向对象的指针,只能定义为“grand”类型,类指针只能通过类生成的对象来使用!!!!

  然后(int *)强制类型转换,通过定义2个相同的指针,来达到我们的目的,因为第一个不能用

 

 1 #include<iostream>
 2  using namespace std;
 3  class A{
 4  
 5  public: A(){cout<<"constructor a"<<endl;}
 6  
 7  };
 8 
 9  void main(){
10     A obja;
11     A *ptr_g = &obja;
12 /*    int *ptr_g = &obja;
13     cannot convert from 'class A *' to 'int *'
14     */
15 
16     int * ptr = (int *) ptr_g;
17     cout<<"ptr = "<<ptr<<endl;
18     cout<<"ptr_g = "<<ptr_g<<endl;
19     cout<<"* ptr is " << *ptr<<endl;
20 /*    cout<<"* ptr_g is " << *ptr_g<<endl;
21     no operator defined which takes a right-hand operand
22     of type 'class A' (or there is no acceptable conversion)
23     */
24  }
我的程序

我们能看到ptr和ptr_g指向相同的地址,但是如果不通过对象,只能直接使用ptr哦,相关错误见程序中的注释

 

posted on 2013-05-15 21:17  イケメンおっさん_汪汪  阅读(99)  评论(0编辑  收藏  举报

导航