栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

深入理解C++ 的 引用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

深入理解C++ 的 引用

目录

1.引用

2.引用做函数参数

3. //引用作函数的返回值

//1.不要返回局部变量的引用

//2.函数调用作为函数的左值

4.引用的本质

//reference

//pointer

5.常量引用-常量的引用

//1.

//const

//2.函数形参 const 与 非 const


1.引用

       int a=10;

       int b=20;

       //int &c; //需要初始化

       int &c=a;//不能更改

       c=b;     //赋值操作 非更改引用

       //&c=b;  //不能更改

       cout<

       cout<

       cout<

//    int &&d=b;  //不存在引用的引用

       int *p=&a;

       int *&e=p; //指针的引用

//    int &*f=&b; //不存在引用的指针

2.引用做函数参数

void swap(int& a,int& b);

int _tmain(int argc, _TCHAR* argv[])

{

       int a=10;

       int b=20;

       swap(a,b);

       cout<<"a="<

//引用作函数参数

      

       return 0;

}

void swap(int& a,int& b)

{

       int temp;

       temp=b;

       b=a;

       a=temp;

}

3. //引用作函数的返回值

//

//1.不要返回局部变量的引用

int & fun()

{

       int a=10;//局部变量存放在栈区

       return a;

}

int _tmain(int argc, _TCHAR* argv[])

{

       int &b=fun();

       cout<

       cout<

       return 0;

}

//2.函数调用作为函数的左值

int & fun()

{

       static int a=4;//静态变量 在全局区 可以返回

       return a;

}

int _tmain(int argc, _TCHAR* argv[])

{

       int &ref=fun();

       cout<

       cout<

       fun()=1000;// 函数的返回值为引用 函数调用可以作为左值;

       cout<

       cout<

       return 0;

}

4.引用的本质

//ref:指针常量(指针是常量):指针的指向不能改变

//常量是指针(常量指针)

//int &ref=a;

//<==>  int* const ref=&a;

int main()

{

//reference

       int m=1;int n=2;

       int a=10;

       int &ref=a;

       ref=100;

       cout<<"a="<

       cout<<"ref="<

       ref=2;//ok,只是赋值

       //&ref=n; //error 不能改变引用;

//pointer

       int b=10;

       int *const p=&b;

       *p=100;

       cout<<"b="<

       cout<<"*p="<<*p<

       *p=n;//ok, 只是赋值

       //p=&n; ///error 不能改变指向

       return 0;

//指针常量

Int *const p;

//常量指针

//int const *p 或者 const int *p

//指向常量的常指针

const int * const p;

5.常量引用-常量的引用

void test01(int &a)

{

       a++;

       cout<<"in test: a="<

}

void test02(const int &b)

{

       //b++;改不了

       cout<<"in test: b="<

}

int main()

{

//1.

//const

       //int &ref=10;  error

       const int &ref=10;//编译器的操作:int temp=10; &ref=10;

       //ref=20;//只读不可更改

//2.函数形参 const 与 非 const

       int a=10;

       cout<<"in main: a="<

       test01(a);

       cout<<"in main: a="<

       int b=10;

       cout<<"in main: b="<

       test02(b);

       cout<<"in main: b="<

借鉴:黑马程序员匠心之作

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869499.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号