C++如果在函数中重新声明成员变量,则会发出警告
给定如下所示的结构,
class A {
int test;
void f() { int test; }
}
我遇到了一个奇怪的情况,其中 f() 中的代码在引用 test 时,在 VS2010 下编译,正确引用了函数局部变量,但是,在 gcc 下编译时,错误地引用了成员多变的。我花了很长时间才找到。
无论如何,问题是,gcc 或 VS 中是否有一个选项可以在每次在本地函数作用域中重新声明成员变量时启用编译器警告?
Given a structure such as below
class A {
int test;
void f() { int test; }
}
I just had a curious case in which the code in f(), when referring to test, compiled under VS2010, correctly referred to the function local variable, however, when compiled under gcc, incorrectly referred to the member variable. Took me quite a while to track down.
Anyway, question is, is there an option in gcc or VS to enable compiler warnings every time a member variable is re-declared in a local function scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 GCC 中,
-Wshadow
。来自文档:In GCC,
-Wshadow
. From the documentation:我不知道是否存在这样的选择。
但如果它不存在,那么您可以执行以下操作。事实上,即使存在一些编译器选项来避免问题中的问题,命名约定也是首选,因为它涵盖了更广泛的关注领域:
也就是说,在命名成员变量时使用一些规则,例如在每个成员变量前面加上 < code>m_ 如
m_test
,或使用后缀如test_
。这是许多程序员通常采用的方法,并且在许多公司中,他们在编码时也施加了类似的规则。这样的命名约定不仅有助于避免您遇到的问题,还增加了可读性和可维护性,因为在没有命名约定的情况下,名称
test
并不能表明它是局部变量还是成员变量。但一旦你采用了一些命名约定,这些事情就会变得清晰起来。I don't know if any such option exists.
But if it doesn't exist, then you can do the following. In fact, the naming convention is preferred even if there exists some compiler option to avoid the problem in the question, for it covers broader area of concerns:
That is, use some rules in naming the member variables, such as, prefix each with
m_
as inm_test
, Or use suffix as intest_
. This is the usual approach adopted by many programmers, and in many companies, there is similar rules which they impose when coding.Such naming conventions not only help avoiding the problem you came across, it also increases readability and maintainability, as the name
test
suggests nothing as to whether it is local variable or member variable in the absence of naming conventions. But once you adopt some naming conventions, such things become clear.