您的位置:首页 > 编程语言 > C语言/C++

c++中 *& 和 **& 符号作用说明

2013-11-12 15:04 309 查看
在c++中,尤其是函数调用或者函数返回的时候,通常会遇到调用 引用(&) 或者返回 引用(&) 对象,更甚者函数调用 **(指针的指针),但是“*&”和“**&”却很少看到,到底代表什么意思呢?下面简单介绍一下。

先从基本的开始:

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;
}
好好领悟一下吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: