zoukankan      html  css  js  c++  java
  • C++指针与引用

    1、指针与引用的区别:
    (1)非空区别。引用不能指向空值。
    (2)合法性区别。由于指针可能为空,所以需要测试它以防止它为空。
    (3)可修改区别。引用初始化后不可再被修改。
    (4)内容区别。指针的内容是内存地址,引用只是某块内存的别名。所以指针的大小永远为4,而引用的大小和原变量相同(char为1,int为4)。
    ***Why is an array of reference not possible?***
    Unlike pointer variables and other variables, references have no storage of their own. A reference is simply an alias for an object that already exists in memory (allowing you to refer to the object by its memory address). Since they have no storage of their own it is impossible to create an array of references. You can of course create an array of objects, each of which can then be referenced. You can also have several references to the same object. But you cannot store those references because there is nothing to physically store other than the object itself, which is already stored. For the same reason you cannot reference references nor can you point to references. You can only refer and point to objects (or point to NULL of course).

    2、指定指针的值(指定地址):

    struct struc
    {
        int a;
        char b[20];
        double ccc;
    }
    (struc*) 0表示把0强制转化成一个struc结构的首地址。这样((struc*) 0)->b表示b在struct中的偏移。
    3、指针作为函数参数传递
    记住一点,在函数中对参数作任何改变,都不影响该参数在原程序中的值,所以指针,即地址,在原程序中是不会改变的(只是指针作为参数时,指针所指的指可能在函数中会被修改)。如果你要使地址在原程序中也得到改变(如,在函数中用这个指针去申请内存),那么
    方法I:传递指向指针的指针,如:
    void GetMemory(char **p, int num){
        *p = (char *) malloc(sizeof(char) *num);
    }
    方法II:将指针作为返回值返回
    char* GetMemory(char **p, int num){
        p = (char *) malloc(sizeof(char) *num);
        return p;
    }
    4、指针作为返回值
    如果这个指针是在函数中新创建的,那么指针本身是存在栈中的,随着函数的退出,该指针也被释放。那么要想得到正确的结果,可以:
    方法I:申请全局指针。全局变量是存在内存中的全局区域。
    方法II:申请为static。这样存储在静态存储空间。如:
    const char* strA()
    {
        static char str[] ="hello world";
        return str;
    }
    5、函数指针
    (1)定义函数
    int max(int x, int y) {
        return x>y?x:y;
    }
    (2)声明函数
    int max(int,int);
    (3)声明函数指针并赋值
    int (*p)(int,int) = &max;
    注意函数指针必须带有括号,否则就变成返回值为int*的函数了。
    6、数组指针
    如:int (*a)[10];
    同函数指针一样,数组指针也必须要有括号,否则就变成元素为int*的数组了
    因为sizeof(*a)结果为40,所以a++就是向后移动40个字节。
    7、指针与句柄
    指针标记某个物理内存地址
    句柄指向的空间存放着资料在物理内存中的地址。即句柄是指向指针的指针。Windows内存管理器移动对象在内存中的位置后,把对象新的地址告之这个句柄地址来保存。
    8、指针的强制转换
    假设类A和类B中都有f()函数。
    A* pa = new A(); 
    B* pb = (B*)pa; //把pa的类型强制转换为了pb类型,但是pa的地址仍然是指向类A的f()。多态正式利用了这个原理。
  • 相关阅读:
    ZJOI2006 物流运输
    codevs 1403 新三国争霸
    (一) MySQL学习笔记:MySQL安装图解
    多线程同步
    SendMessage和PostMessage区别
    VS2008 MFC 配置 Gdiplus
    IE7常用的几个快捷键 你常用的是哪个
    匆匆的六年 收获了什么
    python 代码题07 sorted函数
    python 代码题06 回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4620314.html
Copyright © 2011-2022 走看看