"a declaration shadows a parameter"是什么意思?

What does it mean that "a declaration shadows a parameter"?

本文关键字:意思 是什么 shadows declaration parameter      更新时间:2023-10-16

我试图使一个函数,返回两倍的整数,我将传递给它。我得到以下错误信息与我的代码:

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

您将x作为参数,然后尝试将其声明为局部变量,这就是关于"阴影"的抱怨所指向的。

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

#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;
}
#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,它会遮蔽你的函数参数。