具有相同名称的变量声明C ++ [英] variables declaration with same name C++

查看:85
本文介绍了具有相同名称的变量声明C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以吗?

Class A{
...
...
};

A a; //Global object

int main()
{
   A a; // Local object
   .
   .
   .
   .
   return 0;
}

在类定义之后已声明了全局对象,但还声明了局部变量.可以吗为什么?

Here a global object has been declared after the class definition, but also a local variable has been declared. Is it ok? Why?

推荐答案

隐藏"对象的声明和另一个声明在更严格的范围内是完全合法的.在您的 main 函数中, a 将引用局部变量.在 main 函数之外, a 将引用全局变量.

It's perfectly legal to "hide" the declaration of an object, with another declaration in tighter scope. Within your main function, a will refer to the local variable. Outside the main function, a will refer to the global variable.

关于是否可以-我要说不".这是一个坏主意,因为这可能会使您的代码混乱,并且更容易意外引入错误.我不建议这样做.

As to whether it's "ok" - I would say "no". It's a bad idea, in that it's likely to make your code confusing, and more prone to accidentally introducing bugs. I wouldn't advise doing it.

这篇关于具有相同名称的变量声明C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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