c++中 *& 和 **& 符号作用说明
2013-11-12 15:04
309 查看
在c++中,尤其是函数调用或者函数返回的时候,通常会遇到调用 引用(&) 或者返回 引用(&) 对象,更甚者函数调用 **(指针的指针),但是“*&”和“**&”却很少看到,到底代表什么意思呢?下面简单介绍一下。
先从基本的开始:
1、函数返回引用及函数调用引用
引用简单来看,就是一个变量的别名,所以和原来调用函数的实参没有什么区别,就是同体(一样的)。
2、函数传递参数为指针
一般的情况,在上一篇博文中有详细的介绍:http://blog.csdn.net/richerg85/article/details/14450183,这里不再赘述。
函数传参“**”情况,上文也介绍:
那*& 和 **& 符合分别又代表什么呢?
例如int *&p;
int **&p;
其实这两个*& 和 **&是表示引用,*&表示指针的引用,**&表示指针的指针的引用。
举例:
再说一点和标题不想关的,还是上篇文章提到的问题,这里再给个实例:
先从基本的开始:
1、函数返回引用及函数调用引用
引用简单来看,就是一个变量的别名,所以和原来调用函数的实参没有什么区别,就是同体(一样的)。
ostream &operator<<(ostream &output, const AAA &aaa) { output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl; return output; }从上面函数调用到函数返回,output始终都是一个。
2、函数传递参数为指针
一般的情况,在上一篇博文中有详细的介绍:http://blog.csdn.net/richerg85/article/details/14450183,这里不再赘述。
函数传参“**”情况,上文也介绍:
void my_malloc(void** p, int size) { *p = malloc(sizeof(int)*size); } int main() { int *a; my_malloc(&a , 10); return 1; }通过这种调用可以返回修改的对象值。
那*& 和 **& 符合分别又代表什么呢?
例如int *&p;
int **&p;
其实这两个*& 和 **&是表示引用,*&表示指针的引用,**&表示指针的指针的引用。
举例:
void foo(int*& x, int**& y) { // modifying x or y here will modify a or b in main } int main() { int val = 42; int *a = &val; int **b = &a; foo(a, b); return 0; }修改调用函数中的x和y,会直接影响到主函数中的a和b的值。因为他们是引用关系。
再说一点和标题不想关的,还是上篇文章提到的问题,这里再给个实例:
void pass_by_value(int* p) { //Allocate memory for int and store the address in p p = new int; } void pass_by_reference(int*& p) { p = new int; } int main() { int* p1 = NULL; int* p2 = NULL; pass_by_value(p1); //p1 will still be NULL after this call pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory return 0; }好好领悟一下吧!
相关文章推荐
- C++中&符号的一个重要作用——引用
- C++中引用符号“&”的作用总结
- 托管c++中的资源管理--- "~"和"!"符号的作用
- c++重载<, +, +=, =, ==, <<, >>等符号
- 解决linux eclipse c++找不到符号或者~~~name a type的问题 && c++11
- C++中*和&符号
- C++ 引用符号的用法 &
- 为什么要同时使用和&符号(c++) 转载
- 无符号变量转有符号变量 && C++整型赋值越界处理(VC++)
- php中函数前加&符号的作用分解
- operator=(LONG);报 "error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int"的处理方法
- CMD文件的编写说明,比较详细的 1·什么是CMD文件,它有什么作用。
- sed匹配并追加内容&符号作用
- 关于c++提取符号“>>”的重载问题
- C/C++基础问答(2):C和C++函数互相调用,extern "C"的作用
- C++ "#"的作用和用法
- C++ #include <iostream> #include <iostream.h> #include <string.h>区别及作用
- 【c++语言基础】在c++里&符号的用法
- C、C++等语言常见符号作用总结
- c, c++函数名编译符号修饰符说明