什么是“&"在C ++中意味着什么? [英] What does '&' mean in C++?
问题描述
'&'是什么在C ++中意味着什么?
What does '&' mean in C++?
与功能内一样
void Read_wav::read_wav(const string &filename)
{
}
它在C语言中的等效含义是什么?
And what is its equivalent in C?
如果我想将上述C ++函数转换为C函数,该怎么办?
If I want to transform the above C++ function into a C function, how would I do it?
推荐答案
在这种情况下,&将变量作为引用.
In that context, the & makes the variable a reference.
通常,当您将变量传递给函数时,该变量将被复制,并且该函数将在副本上运行.函数返回时,原始变量不变.传递引用时,即使函数返回后,也不会进行复制,也不会显示该函数所做的更改.
Usually, when you pass an variable to a function, the variable is copied and the function works on the copy. When the function returns, your original variable is unchanged. When you pass a reference, no copy is made and changes made by the function show up even after the function returns.
C没有引用,但是C ++引用在功能上与C中的指针相同.实际上唯一的区别是,在使用它们时必须取消引用指针:
C doesn't have references, but a C++ reference is functionally the same as a pointer in C. Really the only difference is that pointers have to be dereferenced when you use them:
*filename = "file.wav";
但是引用可以像原始变量一样使用:
But references can be used as though they were the original variable:
filename = "file.wav";
表面上,引用应该永远不会为空,尽管这并非不可能.
Ostensibly, references are supposed to never be null, although it's not impossible for that to happen.
等效的C函数为:
void read_wav(const char* filename)
{
}
这是因为C没有 string
.在C中,通常的做法是在需要字符串时将指针发送到字符数组.与C ++中一样,如果您输入字符串常量
This is because C doesn't have string
. Usual practice in C is to send a pointer to an array of characters when you need a string. As in C++, if you type a string constant
read_wav("file.wav");
类型为 const char *
.
这篇关于什么是“&"在C ++中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!