//// Created by pengshuai on 2022年3月26日.//#include <iostream>using namespace std;struct A{A(int) {}operator bool() const {return true;}};struct B{explicit B(int) {}explicit operator bool() const {return true;}};void doA(A a) {}void doB(B a) {}int main(){A a1(1); // OK:直接初始化A a2 = 1; // OK:复制初始化A a3{ 1 }; // OK:直接列表初始化A a4 = { 1 }; // OK:复制列表初始化A a5 = (A)1; // OK:允许 static_cast 的显式转换doA(1); // OK:允许从 int 到 A 的隐式转换if (a1) {cout << "A True!\n";} // OK:使用转换函数 A::operator bool() 的从 A 到 bool 的隐式转换bool a6(a1); // OK:使用转换函数 A::operator bool() 的从 A 到 bool 的隐式转换bool a7 = a1; // OK:使用转换函数 A::operator bool() 的从 A 到 bool 的隐式转换bool a8 = static_cast<bool>(a1); // OK :static_cast 进行直接初始化B b1(1); // OK:直接初始化// B b2 = 1; // 错误:被 explicit 修饰构造函数的对象不可以复制初始化B b3{ 1 }; // OK:直接列表初始化// B b4 = { 1 }; // 错误:被 explicit 修饰构造函数的对象不可以复制列表初始化B b5 = (B)1; // OK:允许 static_cast 的显式转换// doB(1); // 错误:被 explicit 修饰构造函数的对象不可以从 int 到 B 的隐式转换if (b1) {cout << "B True!\n";} // OK:被 explicit 修饰转换函数 B::operator bool() 的对象可以从 B 到 bool 的按语境转换bool b6(b1); // OK:被 explicit 修饰转换函数 B::operator bool() 的对象可以从 B 到 bool 的按语境转换// bool b7 = b1; // 错误:被 explicit 修饰转换函数 B::operator bool() 的对象不可以隐式转换bool b8 = static_cast<bool>(b1); // OK:static_cast 进行直接初始化}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。