[英]Problems with functions parameters in pass by references in C++
I am newbie in c++ and just learning it. 我是C ++的新手,只是学习而已。 I have written the following code.
我写了下面的代码。
#include<iostream>
#include<cstdio>
using namespace std;
void first(int &x,int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<x+i;
}
cout<<endl;
}
void second(int *x,int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<*x+i;
}
cout<<endl;
}
int main()
{
int exm[5]={1,2,3,4,5};
first(exm[0],5);
second(exm,5);
return 0;
}
this program gives output correctly.but the problem is i don't understand the differences between using & and * in function parameters... both are the techniques of passing arguments by references and when we pass by reference we just send the memory address... but in function first when i tried to call the function as follows 这个程序可以正确输出。但是问题是我不理解在函数参数中使用&和*之间的区别...都是通过引用传递参数的技术,当我们通过引用传递参数时,我们只是发送内存地址。 ..但是当我尝试如下调用该函数时,首先在函数中
first(exm,5);
function occurred an error. 函数发生错误。 why ?
为什么呢? but when i called the function as follows
但是当我如下调用该函数时
first(exm[0],5);
it compiled properly and gave right output...but i know that the both calling is equivalent... then why this error occured? 它正确编译并给出正确的输出...但是我知道两个调用都是等效的...那么为什么会发生此错误?
what is the difference between using & and * in function parameters? 在功能参数中使用&和*有什么区别?
The type of the variable exm
is int[5]
, which doesn't meet the signature of first(int &x,int n)
. 变量
exm
的类型是int[5]
,它不符合first(int &x,int n)
的签名。
But int[N]
can be converted implicitly to int*
that points to the first element of the array, hence second(exm,5)
can compile. 但是
int[N]
可以隐式转换为指向数组的第一个元素的int*
,因此second(exm,5)
可以编译。
what is the difference between using & and * in function parameters?
在功能参数中使用&和*有什么区别?
It's the difference between a reference and a pointer. 这是引用和指针之间的区别。
There are lots of differences between them. 它们之间有很多差异。
In this case, I think the biggest difference is whether it accepts NULL or not. 在这种情况下,我认为最大的区别在于它是否接受NULL。
See: 看到:
- What are the differences between a pointer variable and a reference variable in C++? -C ++中的指针变量和引用变量之间有什么区别?
- Are there benefits of passing by pointer over passing by reference in C++? - 在C ++中通过指针传递比通过引用传递有好处吗?
- difference between a pointer and reference parameter? - 指针和引用参数之间的区别?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.