问题描述
如果有一个全局变量,并且该函数的参数名称相同,并且所需结果是局部变量和全局变量的和,那么在这种特定情况下如何引用全局函数?我知道这样做不是个好主意。但只是要求好奇。
int foo = 100;
int bar(int foo)
{
int sum = foo + foo; //总和添加局部变量和全局变量
返回总和;
}
int main()
{
int result = bar(12);
返回0;
}
到目前为止,最好的选择是重命名函数参数,所以它不会与全局变量冲突,所以不需要规避。
假设重命名选项不可接受,请使用<$ c在全球范围内引用 本地名称和全局名称之间的冲突很糟糕 - 它们导致混淆 - 所以它值得回避他们。你可以在GCC中使用 If there is a global variable and the function has a parameter with the same name, and desired result is the sum of the local and global variable, how can we refer the global function in this particular situation? I know its not good idea to do so. But asking just for curiosity. By far the best choice is to rename the function parameter so it does not conflict with the global variable, so there is no need for circumventions. Assuming the rename option is not acceptable, use Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the 这篇关于如何引用与C ++中的局部变量同名的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! foo
:
<$ p $ c> $ p> #include< iostream>
int foo = 100;
int bar(int foo)
{
int sum = foo + :: foo; //总和添加局部变量和全局变量
返回总和;
}
int main()
{
int result = bar(12);
cout<<结果< \\\
;
返回0;
$ / code> -Wshadow
选项( g ++
和 gcc
用于C代码)报告带阴影声明的问题;结合 -Werror
,它会停止代码编译。int foo = 100;
int bar(int foo)
{
int sum=foo+foo; // sum adds local variable and a global variable
return sum;
}
int main()
{
int result = bar(12);
return 0;
}
::foo
to refer to foo
at the global scope:#include <iostream>
int foo = 100;
int bar(int foo)
{
int sum = foo + ::foo; // sum adds local variable and a global variable
return sum;
}
int main()
{
int result = bar(12);
cout << result << "\n";
return 0;
}
-Wshadow
option with GCC (g++
, and with gcc
for C code) to report problems with shadowing declarations; in conjunction with -Werror
, it stops the code compiling.