C++ 中相同的类成员名称和函数参数名称

发布于 2024-08-19 14:06:27 字数 436 浏览 7 评论 0原文

我有一个简单的对象,其中包含一些[公共]数据。

我想保持界面干净,所以我不想对可公开访问的变量的名称或函数参数的名称进行任何预/后修复。

也就是说,我最终做了这样的事情:

template<typename T> struct Foo
{
  explicit Foo(T x) : x(x) // This [i.e., x(x)] seems to be doing the "Right Thing", but is this well defined?
  {/*            ^ 
       No pre-/post- fixing.
   */
  }

  T x; // No pre-/post- fixing.
};

只是重申:我要问的是这是否是明确定义的行为。不是我是否应该这样做...

谢谢。

I have a simple object that holds some [public] data.

I want to keep my interface clean, so I don't want to pre-/post- fix anything to the names of the publically accessible variables nor to the names of my function arguments.

That said, I ended up doing something like this:

template<typename T> struct Foo
{
  explicit Foo(T x) : x(x) // This [i.e., x(x)] seems to be doing the "Right Thing", but is this well defined?
  {/*            ^ 
       No pre-/post- fixing.
   */
  }

  T x; // No pre-/post- fixing.
};

Just to reiterate: All I'm asking is whether this is well defined behavior. Not whether I should or shouldn't be doing this...

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

美男兮 2024-08-26 14:06:27

是的,这很好,而且完全标准。

局部变量在名称查找中总是排在第一位,但初始化列表中的 x(...) 显然只能引用成员变量[编辑:或基类]。

如果您不使用初始化列表,则必须编写:

explicit Foo(T x)
{
    this->x = x;
}

Yes, that's fine, and perfectly standard.

Local variables always come first in a name lookup, but the x(...) in an initialization list can obviously only refer to member variables [edit:or a base class].

If you didn't use the initialization list, you would have to write:

explicit Foo(T x)
{
    this->x = x;
}
鸵鸟症 2024-08-26 14:06:27

特别是对于构造函数的初始化列表,它是定义良好的行为——因为您只能初始化成员或基类,所以其中之一与参数名称之间没有歧义。

然而,在几乎任何其他情况下,您都会造成歧义。特别是,您的标题仅指“函数” - 对于除 ctor 之外的任何函数,这都不起作用。即使在 ctor 的体内,它也不起作用——“特殊”处理纯粹是在 ctor 的初始化列表中。

Specifically for the initializer list of a ctor, it's well-defined behavior -- since you can only initialize a member or base class, there's no ambiguity between one of those and the name of a parameter.

Under almost any other circumstance, however, you'll create an ambiguity. In particular, your title simply refers to "function" -- and for any function other than the ctor, this won't work. Even inside the body of the ctor, it won't work -- the "special" treatment is purely within the initializer list of a ctor.

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