- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 120字
- 2021-06-10 18:28:14
Marking constructors as explicit
In some cases, you do not want to allow the implicit conversion between one type that is passed as a parameter of the constructor of another type. To do this, you need to mark the constructor with the explicit specifier. This now means that the only way to call the constructor is using the parentheses syntax: explicitly calling the constructor. In the following code, you cannot implicitly convert a double to an object of mytype:
class mytype
{
public:
explicit mytype(double x);
};
Now you have to explicitly call the constructor if you want to create an object with a double parameter:
mytype t1 = 10.0; // will not compile, cannot convert
mytype t2(10.0); // OK