C++ “声明隐藏参数”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32311372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does it mean that "a declaration shadows a parameter"?
提问by grandx
I am trying to make a function that returns double the integer number that I will pass to it. I am getting the following error message with my code:
我正在尝试创建一个函数,该函数返回我将传递给它的整数的两倍。我的代码收到以下错误消息:
declaration of 'int x' shadows a parameter int x; "
'int x' 的声明隐藏了一个参数 int x;”
Here is my code:
这是我的代码:
#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;
}
回答by Scott Hunter
You have x
as a parameter and then try to declare it also as a local variable, which is what the complaint about "shadowing" refers to.
你有x
一个参数,然后尝试将它声明为一个局部变量,这就是关于“阴影”的抱怨所指的。
回答by grandx
I did it because your advice was so helpful, and this is the final result :
我这样做是因为你的建议很有帮助,这是最终结果:
#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;
}
回答by Swapnil
#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;
}
There are some problem with your code. Your declaration and definition of function dies not match. So remove declaration as no necessity of it.
你的代码有问题。您对函数的声明和定义不匹配。所以删除声明,因为它没有必要。
You are declaring local x variable inside function which will shadow your function arguments.
您在函数内部声明了局部 x 变量,该变量将隐藏您的函数参数。