码迷,mamicode.com
首页 > 编程语言 > 详细

C++基础--引用

时间:2019-08-31 10:25:31      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:左值   传递   --   turn   on()   color   复合   指针   name   

引用的概念:

  引用就是对象的另外一个名字,这些名字都指向同一块地址。对其中任何一个名字的操作实际上都是对同一个地址单元的操作。在实际的开发中,引用多用作函数的形参使用。

引用的特点:

  ①、引用是一种复合类型,不能定义引用类型的引用,但可以定义其他类型的引用。

  ②、一个对象可以有多个引用。

  ③、普通引用在使用必须用于与该引用同类型的对象初始化,且一经初始化后不能将这个引用绑定到其他对象。

引用的应用:

1、基础引用:

void testFunction()
{
    int a = 4;
    int &b = a;
    cout<<" a= "<< a <<endl;
    cout<<" b= "<< b <<endl;
    b = 100;
    cout<<" a= "<< a <<endl;
}

2、引用做形参:

  当传入的形参是一个数据结构或是一个对象时,采用引用做形参的好处不会产生临时拷贝,传递参数的效率高且占用空间小。

引用可以引用变量、数据结构,指针。

void testFunction(int &a, int &b)
{
        int temp = 0;
        temp = a;
        a = b;
        b = temp;
}
struct testDemo
{
    int id;
    char name[64];
};

int testGetMem(struct testDemo * &p)
{
    p = (struct testDemo *)malloc(sizeof(struct testDemo));
    if( p == NULL)
    {
        return (-1);
    }
    p->id = 100;
    strcpy(p->name,"testName");
    return 0;
}

int main()
{
    struct testDemo *fp;
    testGetMem(fp); 
    cout<<fp->id<<endl;
    cout<<fp->name<<endl;
    return 0;
}

3、引用做为返回值

  引用做函数返回值不能返回局部变量的引用,不能返回函数中new分配内存的引用,容易造成内存泄露,可以返回const 类成员的引用,引用做返回值是可以做左值的。

int& testFunction()
{
    static int a = 10;
    return a;
}

int main()
{
    cout<<testFunction()<<endl;  //打印10
    testFunction()=200;
    cout<<testFunction()<<endl; //打印200
    return 0;
}

 4.const 引用:

  const引用是指向const对象的引用,也叫常引用其定义形式为 const type &name = vale;这样定义不能通过引用对目标变量的值进行修改,从而达到了引用的安全性。

 

void testFunction()
{
    int a = 4;
    const int &b = a;
    cout<<a<<endl;
    b = 200; //报错 assignment of read-only reference ‘b‘
    cout<<a<<endl;    
}

 

C++基础--引用

标签:左值   传递   --   turn   on()   color   复合   指针   name   

原文地址:https://www.cnblogs.com/slwang-27921804/p/11436377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!