zoukankan      html  css  js  c++  java
  • 一点琐碎的指针和引用

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

    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哦,相关错误见程序中的注释

  • 相关阅读:
    C++友元
    C++类与static
    C++const
    reinterpret_cast应用
    学习软件工程课的心得上
    学习软件工程课的心得下
    项目总结报告之假如历史重新再来一次
    人月神话读后感
    团队任务考核
    冲刺周期会议十一
  • 原文地址:https://www.cnblogs.com/kalo1111/p/3080745.html
Copyright © 2011-2022 走看看