C++如果在函数中重新声明成员变量,则会发出警告

发布于 2024-12-20 03:22:24 字数 263 浏览 3 评论 0原文

给定如下所示的结构,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无敌元气妹 2024-12-27 03:22:24

在 GCC 中,-Wshadow。来自文档

每当局部变量或类型声明遮盖另一个变量或类型声明时发出警告
变量、参数、类型或类成员(在 C++ 中),或者每当
内置函数被遮挡。请注意,在 C++ 中,编译器不会
如果局部变量隐藏结构/类/枚举,则发出警告,但如果
它隐藏了显式的 typedef。

In GCC, -Wshadow. From the documentation:

Warn whenever a local variable or type declaration shadows another
variable, parameter, type, or class member (in C++), or whenever a
built-in function is shadowed. Note that in C++, the compiler will not
warn if a local variable shadows a struct/class/enum, but will warn if
it shadows an explicit typedef.

野鹿林 2024-12-27 03:22:24

我不知道是否存在这样的选择。

但如果它不存在,那么您可以执行以下操作。事实上,即使存在一些编译器选项来避免问题中的问题,命名约定也是首选,因为它涵盖了更广泛的关注领域:

class A {
  int m_test;   //use some naming conventions!
  void f() { int test; }
};

也就是说,在命名成员变量时使用一些规则,例如在每个成员变量前面加上 < 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:

class A {
  int m_test;   //use some naming conventions!
  void f() { int test; }
};

That is, use some rules in naming the member variables, such as, prefix each with m_ as in m_test, Or use suffix as in test_. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文