mercredi 31 juillet 2019

Avoiding Implicit Conversion in Constructor. Explicit keyword doesn't help here

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

But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that only object can be created if we pass integer as a parameter e.g. A a1 = A(10)?

#include <iostream>

class A
{
public :
    explicit A(int a)
    {
     num = a;
    }

    int num;
};

int main()
{
    A a1=A(10.0);
    std::cout << a1.num;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire