C++ 中相同的类成员名称和函数参数名称
我有一个简单的对象,其中包含一些[公共]数据。
我想保持界面干净,所以我不想对可公开访问的变量的名称或函数参数的名称进行任何预/后修复。
也就是说,我最终做了这样的事情:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这很好,而且完全标准。
局部变量在名称查找中总是排在第一位,但初始化列表中的 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:
特别是对于构造函数的初始化列表,它是定义良好的行为——因为您只能初始化成员或基类,所以其中之一与参数名称之间没有歧义。
然而,在几乎任何其他情况下,您都会造成歧义。特别是,您的标题仅指“函数” - 对于除 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.