【问题标题】:What does it mean that "a declaration shadows a parameter"?“声明隐藏参数”是什么意思?
【发布时间】:2015-08-31 12:32:45
【问题描述】:

我正在尝试创建一个函数,它返回我将传递给它的整数的两倍。我的代码收到以下错误消息:

'int x' 的声明隐藏了一个参数 int x; "

这是我的代码:

#include <iostream>
int doublenumber();
using namespace std;
int doublenumber(int x)// <-- this is the function which returns double the value .
{
    int x;
    return 2 * x;
    cout << endl;
}
int main()
{
    int a;
    cout << "Enter the number that you want to double it : " << endl;
    cin >> a;
    doublenumber(a);

    return 0;
}

【问题讨论】:

  • 您将局部变量命名为与参数相同。删除doublenumber 中的第一行。此外,该函数的最后一行永远不会像return 之后那样执行。
  • 请努力提供一个没有错误且有意义的标题。
  • 伙计们,在我编辑我的代码后它运行正常,但它永远不会返回双精度值,我不知道为什么? ,有什么建议!?
  • 你永远不会用它做任何事情。试试int n = doublenumber(a); cout &lt;&lt; n &lt;&lt; endl;
  • 我投票重新提出这个问题,因为它是我找到的最好的副本,询问此错误消息的含义。

标签: c++ function integer


【解决方案1】:

您将x 作为参数,然后尝试将其也声明为局部变量,这就是关于“遮蔽”的抱怨所指的内容。

【讨论】:

    【解决方案2】:

    我这样做是因为您的建议很有帮助,这就是最终结果:

    #include <iostream>
    using namespace std;
    
    int doublenumber(int x)
    {
        return 2*x;
    }
    
    int main()
    {
        int a;
        cout << "Enter the number that you want to double it : " << endl;
        cin>>a;
        int n= doublenumber(a);
        cout << "the double value is : " << n << endl;
        return 0;
    }
    

    【讨论】:

      【解决方案3】:
      #include <iostream>
      using namespace std;
      int doublenumber(int x)
      {
      return 2*x;
      }
      int main()
      {
      int a;
      cout << "Enter the number that you want to double it : " << endl;
      cin>>a;
      int d = doublenumber(a);
      
      cout << "Double : " << d << endl;
      
      return 0;
      }
      

      您的代码有问题。您对函数的声明和定义不匹配。所以删除声明是不必要的。

      您在函数内部声明局部 x 变量,这将影响您的函数参数。

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
      • @swapnil 非常感谢你,但你的代码对我不起作用,缺少一些东西:)
      • @grandx 我明白你的意思...删除行 int doublenumber();因为您的函数定义和声明不匹配。甚至不需要函数声明,因为我们在 main 之前提供了定义。
      猜你喜欢
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多