【问题标题】:Problems with functions parameters in pass by references in C++C++中通过引用传递函数参数的问题
【发布时间】:2014-09-26 04:18:52
【问题描述】:

我是 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;
}

这个程序给出了正确的输出。但问题是我不明白在函数参数中使用 & 和 * 之间的区别...... 两者都是通过引用传递参数的技术,当我们通过引用传递时,我们只是发送内存地址...... 但是当我尝试按如下方式调用函数时,首先在函数中

first(exm,5);

函数发生错误。 为什么 ? 但是当我按如下方式调用函数时

first(exm[0],5);    

它编译正确并给出了正确的输出...但我知道这两个调用是等效的... 那么为什么会出现这个错误呢?
在函数参数中使用 & 和 * 有什么区别?

【问题讨论】:

标签: c++ function pass-by-reference


【解决方案1】:

变量exm的类型是int[5],不符合first(int &amp;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?

【讨论】:

  • 谢谢...但是,在第二(exm,5); exm 不传递 exm[0] 的内存地址吗?
  • @KhairulBasar 是的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
相关资源
最近更新 更多