这是使用 C++ 的示例吗? “明确”关键字正确吗?

发布于 2024-12-05 12:24:15 字数 547 浏览 1 评论 0原文

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

发布评论

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

评论(1

独守阴晴ぅ圆缺 2024-12-12 12:24:15

在他的讨论中,Stroustrup 提到直接初始化,例如

Sick s2(2.1);

如果存在任何显式构造函数,则仅考虑标记为显式构造函数。这不是我对几个编译器(包括 GCC 4.6.1 和 MSVC 16/VS 2010)的经验,而且我在标准中找不到这样的要求(尽管如果有人能指出的话我会很感兴趣)。

但是,如果在初始化器中使用 int,我认为该示例将显示 Stroustrup 想要演示的内容:

#include <iostream>

struct Sick
{
    Sick(double d)       { std::cout << "double " << d << "\n"; }
    explicit Sick(int i) { std::cout << "int " << i << "\n"; }
};


int main()
{
    Sick s1 = 2;
    Sick s2(2);
}

运行上面的内容将显示:

double 2
int 2

显示两个明显等效的初始化实际上选择了不同的构造函数。

(或者正如 Truncheon 在问题中提到的 - 我错过了 - explicit 关键字应该位于 Sick(double d) 构造函数上)。

In his discussion, Stroustrup mentions that a direct initialization, such as

Sick s2(2.1);

will consider only constructors marked explicit if there are any explicit 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:

#include <iostream>

struct Sick
{
    Sick(double d)       { std::cout << "double " << d << "\n"; }
    explicit Sick(int i) { std::cout << "int " << i << "\n"; }
};


int main()
{
    Sick s1 = 2;
    Sick s2(2);
}

Running the above will display:

double 2
int 2

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 the Sick(double d) constructor).

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