关于explicit 函数 形参类型转换的疑惑
2022.3.31
今日学习发现,
定义了一个testclass_explicit类,有如下构造函数
testclass_explicit(int data) :pridata(data){ cout << "pridata " << pridata << endl; };
testclass_explicit(char c) :prichar(c){ cout << "prichar " << c << endl; };
再不添加explicit关键字的情况下,如下调用显然正常
testclass_explicit t1(9);
testclass_explicit t2 = 67;
testclass_explicit t3('a');
testclass_explicit t4 = 'f';
输出:
//pridata 9
// pridata 67
// prichar a
// prichar f
当对其中一个进行隐式抑制以后,explicit testclass_explicit(int data),我最开始想要的结果应该是int形参的隐式类型转换被抑制,所以 testclass_explicit t2 = 67; 这句应当编译报错,
但实际上运行时调用了了char形参的构造函数,
输出
//pridata 9
// prichar C //调用了了char形参的构造函数,
// prichar a
// prichar f
这里我的疑问有两个
一,为什么最终去调用了char的构造函数,是因为对于int形参,刚好存在char形参函数,所以做了从int到char的类型匹配吗,这看起来像是函数重载中的类型转换,
二,那如何实现完全抑制形参为int的构造函数的隐式转换呢
等改天看懂了再回来解答自己
2022.4.1
对于问题一
c++ primer 517 提到,不建议在一个类中定义多个跟算术类型有关的转换规则,会导致二义性,
因为算术类型之间本身存在标准类型转换,而标准转换的优先级决定了编译器会采用哪种匹配(从 char 到 int 显然比 char 到double 更合适,优先级更高)

浙公网安备 33010602011771号