Avoiding implicit conversion in constructor. The 'explicit' keyword doesn't help here

前端 未结 7 2053
闹比i
闹比i 2020-12-29 18:07

I am able to avoid the implicit conversion of a constructor using the explicit keyword. So now, conversions like A a1 = 10; can be avoided.

7条回答
  •  盖世英雄少女心
    2020-12-29 18:15

    To avoid int->double conversions everywhere, not only in your case. With g++ you can use -Wconversion -Werror. Note that it'll be allowed in your particular case, because the compiler understands that 10.0 is literal, but it will fail compilation for:

    class A
    {
    public:
        explicit A(int a)
        {
            num = a;
        }
    
        int num;
    };
    
    int main()
    {
        double x = 10;
        A a1 = A(x);
        static_cast(a1);
        return 0;
    }
    

    Compiler explorer

提交回复
热议问题