在C++中通过引用传递函数参数的问题

问题描述:

我是C++中的新手,刚刚学习它。 我写了下面的代码。在C++中通过引用传递函数参数的问题

#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; 
} 

此程序会输出correctly.but问题是我不明白,在功能参数使用&和*之间的差异...... 都是通过引用传递参数的技术,当我们路过参考我们只是送内存地址... 但在功能第一,当我试图调用该函数如下发生了错误

first(exm,5); 

功能。 为什么? 但是当我调用该函数如下

first(exm[0],5);  

它正确的编译,并给右输出...但我知道,这两个调用相当于... 那么为什么这个错误发生?
在函数参数中使用&和*有什么区别?

+1

的可能重复(http://stackoverflow.com/questions/620604/difference-between -a-pointer-and-reference-parameter) – 2014-09-26 04:26:47

变量exm的类型是int[5],它不符合first(int &x,int n)的签名。
int[N]可以隐式转换为int*指向数组的第一个元素,因此second(exm,5)可以编译。

在功能参数中使用&和*有什么区别?

这是参考和指针之间的区别。

它们之间有很多不同之处。
在这种情况下,我认为最大的区别是它是否接受NULL。

参见:[?一个指针和基准参数之间的差异]
- What are the differences between a pointer variable and a reference variable in C++?
- - Are there benefits of passing by pointer over passing by reference in C++?
difference between a pointer and reference parameter?

+0

谢谢...但是,在第二(exm,5);不exm传递exm [0]的内存地址? – 2014-09-26 05:16:17

+0

@KhairulBasar是的,它的确如此。 – Ripple 2014-09-26 07:13:50