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

百般思念 提交于 2019-12-12 03:23:22

问题


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;
}

回答1:


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)

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

A a(3.3);

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;



回答2:


It works in the other way around. Let's define in addition to your code

void f(A a)
{
}

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

Without the word explicit it would compile, with the explicit it would report an error. The keyword forbids casting from integer to A in situations like this.



来源:https://stackoverflow.com/questions/34129643/explicit-keyword-in-g-has-no-effect-for-simple-constructor-not-copy-assignm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!