简体   繁体   English

C ++函数输入参数按引用还是按指针

[英]C++ function input argument by reference vs by pointer

I am new to C++ and have done only MATLAB earlier. 我是C ++的新手,并且以前只做过MATLAB。

My Q is about the input argument of the following functions, which call variables by value,reference and pointer. 我的Q与以下函数的输入参数有关,这些函数通过值,引用和指针来调用变量。

void SwapbyValue (int a, int b){
// Usual swapping code
}

void SwapbyRef (int &a, int &b){
// Usual swapping code
}

void SwapbyPoint(int *a,int *b){
//Usual swapping code
} 

Since my Q isn't about how the above functions work but rather about how I call them, I've left out the code. 由于我的问题与上述功能的工作方式无关,而与我如何调用它们有关,因此我省略了代码。 So, I understand we call the above functions by typing SwapbyRef (i1,i2),SwapbyRef (i1,i2) and SwapbyPoint(&i1,&i2) when i1 and 12 are int. 因此,我知道我们通过在i1和12为int时键入SwapbyRef(i1,i2),SwapbyRef(i1,i2)和SwapbyPoint(&i1,&i2)来调用上述函数。

That confuses me the life out of me. 那使我感到困惑。 Okay, I get that the first function takes in values and makes sense. 好的,我知道第一个函数接受值并且有意义。 But in the second one, calling by just i1 and i2 doesn't make sense as when the function is defined, we set its input as &a and not just a but it still runs. 但是在第二个函数中,仅通过i1和i2进行调用就没有意义,因为在定义函数时,我们将其输入设置为&a而不仅是a ,它仍然可以运行。 Again in the third, we set the input argument as a pointer ie *a but we're passing an address &a (like 0x7956a69314d8) when we call it. 再次在第三个示例中,我们将输入参数设置为指针*a但是在调用它时传递了地址&a (例如0x7956a69314d8)。

Why does it run when we pass the wrong kind of input to the function? 当我们向函数传递错误类型的输入时,为什么它会运行? For example,a Matlab analogy,it looks like passing a char to a int function. 例如,以Matlab为例,它看起来像将char传递给int函数。 Help! 救命!

int &a is a reference to an int, meaning, it will accept all int variables that already exist. int&a是对int的引用,表示它将接受所有已经存在的int变量。 What you cannot do is for example SwapbyRef(4, 5) using SwapbyRef (int &a, int &b) , because 4 and 5 are temporary ints that do not exist somewhere in memory as variables. 您无法执行的操作例如是使用SwapbyRef (int &a, int &b) SwapbyRef(4, 5) SwapbyRef (int &a, int &b) ,因为4和5是临时int,它们在变量中不存在于内存中。

Btw, you should probably just look up what a reference in c++ is. 顺便说一句,您可能应该只查找c ++中的引用是什么。 That would help you most, I think. 我认为,这对您最有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM