g++ 中的 'explicit' 关键字对简单构造函数没有影响(不是 copy/assignment 构造函数)?

'explicit' keyword in g++ has no effect for simple constructor (not copy/assignment constructor)?

任何人都可以解释为什么以下代码可以编译吗?我希望它会在 double 常量 3.3 无法转换为 int 的情况下出现错误,因为我将构造函数声明为 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;
}

反之亦然。除了你的代码

,让我们来定义
void f(A a)
{
}

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

没有 explicit 会编译,有 explicit 会报错。在这种情况下,关键字禁止从整数转换为 A

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

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

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

在您的情况下,您使用直接初始化来构造类型A的实例,方法是:

A a(3.3);

explicit 关键字不会阻止编译器将您的参数从 double 类型隐式转换为 int。它阻止你做这样的事情:

A a = 33;