如何引用与C ++中的局部变量同名的全局变量? [英] How to refer to a global variable which has the same name as a local variable in C++?

查看:120
本文介绍了如何引用与C ++中的局部变量同名的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个全局变量,并且该函数的参数名称相同,并且所需结果是局部变量和全局变量的和,那么在这种特定情况下如何引用全局函数?我知道这样做不是个好主意。但只是要求好奇。

  int foo = 100; 

int bar(int foo)
{
int sum = foo + foo; //总和添加局部变量和全局变量
返回总和;
}

int main()
{
int result = bar(12);
返回0;
}


解决方案

到目前为止,最好的选择是重命名函数参数,所以它不会与全局变量冲突,所以不需要规避。



假设重命名选项不可接受,请使用<$ 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>

本地名称和全局名称之间的冲突很糟糕 - 它们导致混淆 - 所以它值得回避他们。你可以在GCC中使用 -Wshadow 选项( g ++ gcc 用于C代码)报告带阴影声明的问题;结合 -Werror ,它会停止代码编译。


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.

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

解决方案

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

Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the -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.

这篇关于如何引用与C ++中的局部变量同名的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆