class MyFloat {On the last two lines, implicit conversions occur from int to MyFloat, which are perfectly acceptable for this simple class. However, if the implicit conversion was not desired, the explicit keyword can be added in front of the constructor to prevent it. The compiler will now generate errors for the last two lines above. These lines can be rewritten to work:
float m_value;
public:
MyFloat(int value): m_value(value) {}
float value(void) { return m_value; }
};
float square(MyFloat myFloat) {
return myFloat.value() * myFloat.value();
}
MyFloat something = 47;
std::cout << square(12) << std::endl;
MyFloat something = MyFloat(47);This is a contrived example and would probably make sense to allow the implicit conversion in this class, however, this is not the case with the classes used in this project. Therefore, the explicit keyword was added to all the constructors that take a single argument, which included the CommandLine, Parser, Tester, Token and Translator classes.
std::cout << square(MyFloat(12)) << std::endl;
The most glaring constructor requiring explicit was the Token constructor Token(int column = -1) that would have allowed a statement like Token token = 47;, which does not make sense (a token should not be assigned an integer).
[commit 5979939788]
No comments:
Post a Comment
All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)