g ++中的'explicit'关键字对简单构造函数(不是复制/赋值构造函数)无效吗? [英] 'explicit' keyword in g++ has no effect for simple constructor (not copy/assignment constructor)?

查看:92
本文介绍了g ++中的'explicit'关键字对简单构造函数(不是复制/赋值构造函数)无效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么以下代码会编译吗?我希望它会得到一个错误,其中 double 常量 3.3 不能转换为 int ,因为我将构造函数声明为明确的.

Can anyone explain why the following code compiles? I expect it to get an error where the double constant 3.3 can not be converted to int, since I declare the constructor to be explicit.

class A
{
public:
    int n;
    explicit A(int _n);
};

A::A(int _n)
{
    n = _n;
}

int main()
{
    A a(3.3); // <== I expect this line to get an error.
    return 0;
}

推荐答案

显式class_name(params)(1)
显式运算符类型()(自C ++ 11起)(2)

explicit class_name ( params ) (1)
explicit operator type ( ) (since C++11) (2)

1)指定仅考虑将此构造函数用于直接初始化(包括显式转换)

1) specifies that this constructor is only considered for direct initialization (including explicit conversions)

2)指定仅将用户定义的转换函数用于直接初始化(包括显式转换)

2) specifies that this user-defined conversion function is only considered for direct initialization (including explicit conversions)

在您的情况下,您使用直接初始化通过执行以下操作来构造类型为 A 的实例:

In your case you are using direct initialization to construct an instance of type A by doing this:

A a(3.3);

显式关键字不会阻止编译器隐式地从int的双精度型.它阻止您执行以下操作:

The explicit keyword does not stop the compiler from implicitly casting your argument from a double type to an int. It stops you from doing something like this:

A a = 33;

这篇关于g ++中的'explicit'关键字对简单构造函数(不是复制/赋值构造函数)无效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆