这是使用 C++ 的示例吗? “明确”关键字正确吗?
在 YouTube 上的 GoogleTechTalks 视频中,Bjarne Stroustrup 谈论了即将推出的 C+ +0x 标准。在视频中,他提到了以下示例:
#include <iostream>
struct Sick
{
Sick(double d) { std::cout << d << "\n"; }
explicit Sick(int i) { std::cout << i << "\n"; }
};
int main()
{
Sick s1 = 2.1;
Sick s2(2.1);
}
他是否打算在 Sick(double)
而不是 Sick(int)
之前放置 explicit
关键字,为了突出在某些上下文中与隐式转换相关的问题?
In a GoogleTechTalks video on Youtube, Bjarne Stroustrup talks about the upcoming C++0x standard. In the video he mentions the following example:
#include <iostream>
struct Sick
{
Sick(double d) { std::cout << d << "\n"; }
explicit Sick(int i) { std::cout << i << "\n"; }
};
int main()
{
Sick s1 = 2.1;
Sick s2(2.1);
}
Did he mean to place the explicit
keyword before Sick(double)
rather than Sick(int)
, in order to highlight problems associated with implicit conversions in certain contexts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在他的讨论中,Stroustrup 提到直接初始化,例如
如果存在任何显式构造函数,则仅考虑标记为显式构造函数。这不是我对几个编译器(包括 GCC 4.6.1 和 MSVC 16/VS 2010)的经验,而且我在标准中找不到这样的要求(尽管如果有人能指出的话我会很感兴趣)。
但是,如果在初始化器中使用 int,我认为该示例将显示 Stroustrup 想要演示的内容:
运行上面的内容将显示:
显示两个明显等效的初始化实际上选择了不同的构造函数。
(或者正如 Truncheon 在问题中提到的 - 我错过了 -
explicit
关键字应该位于Sick(double d)
构造函数上)。In his discussion, Stroustrup mentions that a direct initialization, such as
will consider only constructors marked
explicit
if there are anyexplicit
constructors. That's not my experience with several compilers (including GCC 4.6.1 and MSVC 16/VS 2010), and I can't find such a requirement in the standard (though I'd be interested if someone can point it out).However, if ints are used in the initializers, I think the example would show what Stroustrup meant to demonstrate:
Running the above will display:
Shows that the two apparently equivalent initializations actually select different constructors.
(Or as Truncheon mentioned in the question - and I missed - that the
explicit
keyword should be on theSick(double d)
constructor).