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.
But still I can initialize A a1 = A(20.2);
. How can I disable the object creation such that an object can only be created if we pass an 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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…