混淆C ++指针和参考主题 [英] Confusion over C++ pointer and reference topic

查看:116
本文介绍了混淆C ++指针和参考主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的以下参数传递机制有什么区别?

What is the difference between the following parameter passing mechanisms in C++?

void foo(int &x) 
void foo(int *x)
void foo(int **x)
void foo(int *&x)



I'd like to know in which case the parameter is being passed by value or passed by reference.

推荐答案

void foo(int &x)

将引用传递给整数。这是一个输入/输出参数,可以像函数中的常规整数一样使用。值会传回给调用者。

passes a reference to an integer. This is an input/output parameter and can be used like a regular integer in the function. Value gets passed back to the caller.

void food(int *x)

将指针传递给整数。这是一个输入/输出参数,但它像一个指针一样使用,必须取消引用(例如 * x = 100; )。您还需要检查它不为null。

passes a pointer to an integer. This is an input/output parameter but it's used like a pointer and has to be dereferenced (e.g. *x = 100;). You also need to check that it's not null.

void foo(int **x)

传递指向整数指针的指针。这是一个类型为整数指针的输入/输出参数。如果要更改整数值的值(例如 * x =& m_myInt; ),请使用此选项。

passes a pointer to a pointer to an integer. This is an input/output parameter of type integer pointer. Use this if you want to change the value of an integer point (e.g. *x = &m_myInt;).

void foo(int *&x)

将指向的指针传递给整数。如上所述,但不需要解引用指针变量(例如 x =& m_myInt; )。

passes a reference to a pointer to an integer. Like above but no need to dereference the pointer variable (e.g. x = &m_myInt;).

希望有意义。我建议使用typedef来简化指针和引用符号的使用。

Hope that makes sense. I would recommend using typedefs to simplify the use of pointers and reference symbols.

这篇关于混淆C ++指针和参考主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆