c++引用和指针的区别

来源:互联网 发布:阿里云退款电话 编辑:程序博客网 时间:2024/06/03 09:26

1.(1)C语言中的&
C语言中的&仅仅代表取址,C语言中没有引用这个概念,C++中有,是C++和C语言的区别之一。
所以C语言中的&和指针的区别很明显。
C++中的引用与指针的区别
指向不同类型的指针的区别在于指针类型可以知道编译器解释某个特定地址(指针指向的地址)中的内容及大小,而void*指针则只表示一个内存地址,编译器不能通过该指针知道指针所指向对象的类型和大小,因此想要通过void*指针操作对象必须进行类型转化。

  • 相同点:
    1.都是与地址相关的概念;
    指针指向一块内存,它的内容是指内存的地址;
    引用是某块内存的别名;

  • 区别:
    1.指针是一个实体,而引用仅是个别名;
    2.访问内存中的值时,引用使用时无需解引用(*),指针需要解引用;
    3.引用只能在定义时被初始化一次,之后不可变;指针可变;引用“从一而终”;
    4.引用没用const,指针有const,const的指针不可变;
    5.引用不能为空,指针可以为空;
    6.“sizeof 引用”得到的是所指向的变量(对象)的大小,而“sizeof 指针”得到的是指针本身(所指向的变量或对象的地址)的大小;
    7.指针和引用的自增(++)运算意义不一样;

  • 联系
    1.引用在语言内部用指针实现(如何实现?)。
    2.对一般应用而言,把引用理解为指针,不会犯严重语义错误。引用是操作受限了的指针(仅容许取内容操作)。
    引用是C++中的概念,初学者很容易把引用和指针混淆在一起。

void main(){    int a=2;    int &b=a;  //此处b相当于a的别名 注意不是int b=&a;     printf("%d %d",a,b);}

如果用函数传递参数,实现改变某个数的值。

若用C语言,则传递一个指针值(地址),在函数里把指针所指向的内容重新赋值,指针值不会变。

01.#include<stdio.h>  02.  03.int change(int *i)  04.{  05.    (*i) = 100;  06.}  07.  08.int main()  09.{  10.    int a = 60;  11.    printf("%d\n",a);  12.    change(&a);  13.    printf("%d\n",a);  14.    return 0;  15.}  

若用C++语言,则可以用 ”引用参数“

01.#include<stdio.h>  02.  03.int change(int &i)  04.{  05.    i = 100;  06.}  07.  08.int main()  09.{  10.    int a = 60;  11.    printf("%d\n",a);  12.    change(a);  13.    printf("%d\n",a);  14.    return 0;  15.}

C语言用户真心觉得不太习惯C++的这个特性。

深入一步,如果是要改变或创建一个struct指针类型的节点(例如链表节点、二叉树节点)

C语言

01.#include<stdio.h>  02.#include<stdlib.h>  03.  04.struct tree  05.{  06.    int num;  07.    struct tree *l;  08.    struct tree *r;  09.};  10.  11.int createTreeNode(struct tree **p)  12.{  13.    (*p) = (struct tree*)malloc(sizeof(struct tree));  14.    (*p)->l=NULL;  15.    (*p)->r=NULL;  16.    return 0;  17.}  18.  19.int main()  20.{  21.    struct tree *head=NULL;  22.    createTreeNode(&head);  23.    if (head == NULL)   24.        printf("is NULL");  25.    else  26.        printf("is not NULL");  27.      28.    return 0;  29.}<span style="color:#993399;">  30.</span> 

C++语言

01.#include<stdio.h>  02.#include<stdlib.h>  03.  04.struct tree  05.{  06.    int num;  07.    struct tree *l;  08.    struct tree *r;  09.};  10.  11.int createTreeNode(struct tree * &p)  12.{  13.    p = (struct tree*)malloc(sizeof(struct tree));  14.    p->l=NULL;  15.    p->r=NULL;  16.    return 0;  17.}  18.int main()  19.{  20.    struct tree *head=NULL;  21.    createTreeNode(head);  22.    if (head == NULL)   23.        printf("is NULL");  24.    else  25.        printf("is not NULL");  26.      27.    return 0;  28.}  

当然,C++兼容C的语法,也就是说以上的代码都可以在C++里运行。

还有一个关于gcc编译器,怎样用C编译器,怎样用C++编译器。

(1)用C编译器的情况: gcc text.c

(2)用C++编译器的情况: g++ test.c 或者 g++ test.cpp 或者 g++ test.c (也就是用g++命令或者源文件后缀是cpp,则默认是用C++编译器)

参考:http://www.cnblogs.com/tracylee/archive/2012/12/04/2801519.html

0 0