Declaring a local variable within class scope with same name as a class attribute(在类范围内声明一个与类属性同名的局部变量)
问题描述
在观察另一个人的代码时,我意识到在 A 类的方法中,他声明了一个与 A 类的属性同名的本地 int.例如:
While observing another person's code, i realized that within class A's method he declared a local int with the same name as an attribute of class A. For example:
//classA.h
class A{
int Data;
void MethodA();
};
//classA.cpp
//classA.cpp
#include "classA.h"
using namespace std;
void A::MethodA(){
int Data; //local variable has same name as class attribute
Data = 4;
//Rest of Code
}
我发现编译器会接受它而不返回错误很奇怪.在上述情况下,4是分配给本地Data还是A::Data,在更复杂的情况下会导致什么问题?
I found it weird that the compiler would accept it without returning an error. In the above case, would the 4 be assigned to the local Data or A::Data, and what problems could this cause in more complex situations?
推荐答案
局部变量会影响成员一(它的范围更窄).如果你只是写
The local variable will shadow the member one (it has the more narrow scope). If you just write
Data = 4;
您将分配给局部变量Data
.您仍然可以使用
you will assign to the local variable Data
. You can still access the member variable with
this->Data = 4;
这基本上就像
{
int data = 4;
{
int data = 2;
data++; // affects only the inner one
}
}
至于未来的问题:只要您和所有将使用您的代码的人都了解规则并且知道您是故意这样做的,就没有问题.如果您不打算故意这样做,请让您的编译器对此发出警告.
As for problems in the future: As long as you and everyone who will ever work with your code understands the rules and is aware that you did this on purpose there is no problem. If you do not intend to do such things on purpose, make your compiler warn about it.
但是,如果您遵循成员变量的命名方案,那肯定会更省钱,例如附加下划线,如
However, it would certainly be saver if you followed a naming scheme for member variables, e.g. append an underscore like
class A{
int Data_;
void MethodA();
};
这篇关于在类范围内声明一个与类属性同名的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在类范围内声明一个与类属性同名的局部变量


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01