C ++函数:&号对星号 [英] C++ functions: ampersand vs asterisk
问题描述
假设你有一个修改变量的函数。
Let's say you have a function that modifies a variable.
如果你这样编写: void myfunc(int * a)
或像这样 void myfunc(int& a)
?
Should you write it like this: void myfunc(int *a)
or like this void myfunc(int &a)
?
用 myfunc(& b)
调用函数,因此调用者知道 b
将被修改,后者更短,可以简单地用 myfunc(b)
调用。那么哪个是更好的使用?
The former forces you to call the function with myfunc(&b)
so the caller is aware that b
will be modified, but the latter is shorter and can be called simply with myfunc(b)
. So which is better to use? Is there something else I'm missing?
推荐答案
指针(即'*')应该用于传递 NULL是有意义的。
例如,您可以使用NULL来表示需要创建特定对象,或者不需要执行特定操作。
或者如果它需要从非C ++代码调用。 (例如,用于共享库)
Pointers (ie. the '*') should be used where the passing "NULL" is meaningful. For example, you might use a NULL to represent that a particular object needs to be created, or that a particular action doesn't need to be taken. Or if it ever needs to be called from non-C++ code. (eg. for use in shared libraries)
例如。 libc函数 time_t time(time_t * result);
eg. The libc function time_t time (time_t *result);
如果 result
不为NULL,当前时间将被存储。但如果 result
为NULL,则不执行任何操作。
If result
is not NULL, the current time will be stored. But if result
is NULL, then no action is taken.
t需要使用NULL作为有意义的值,然后使用引用(即'&')可能会更少混淆 - 假设是您的项目使用的约定。
If the function that you're writing doesn't need to use NULL as a meaningful value then using references (ie. the '&') will probably be less confusing - assuming that is the convention that your project uses.
这篇关于C ++函数:&号对星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!