Can a single argument constructor with a default value be subject to implicit type conversion
I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument 开发者_运维技巧constructor, or with a constructor that has multiple arguments of which only the first does not have a default value.
However, I was wondering, does a single argument constructor with a default value behave the same as one without a default value when it comes to implicit conversions?The existence of a default value does not stop the single-argument ctor from being used for implicit conversion: you do need to add explicit
if you want to stop that.
For example...:
#include <iostream>
struct X {
int i;
X(int j=23): i(j) {}
};
void f(struct X x) {
std::cout << x.i << std::endl;
}
int main() {
f(15);
return 0;
}
compiles and runs correctly:
$ g++ -Wall -pedantic a.cc
$ ./a.out
15
$
correctly, that is, if you want an int
to become a struct X
implicitly. The =23
part, i.e. the default value for the one argument to the constructor, does not block this.
精彩评论