update dir
This commit is contained in:
parent
f74415846d
commit
71d83ce466
@ -21,7 +21,8 @@
|
|||||||
- [x] [struct那些事](./struct)
|
- [x] [struct那些事](./struct)
|
||||||
- [x] [struct与class那些事](./struct_class)
|
- [x] [struct与class那些事](./struct_class)
|
||||||
- [x] [union那些事](./union)
|
- [x] [union那些事](./union)
|
||||||
- [x] [c实现c++多态](./c_poly)
|
- [x] [c实现c++多态那些事](./c_poly)
|
||||||
|
- [x] [explicit那些事](./explicit)
|
||||||
|
|
||||||
代码运行:
|
代码运行:
|
||||||
全部在linux下用vim编写,使用gcc/g++调试!全部可正常运行!
|
全部在linux下用vim编写,使用gcc/g++调试!全部可正常运行!
|
||||||
|
10
explicit/README.md
Normal file
10
explicit/README.md
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
# explicit(显式)关键字那些事
|
||||||
|
|
||||||
|
- explicit 修饰构造函数时,可以防止隐式转换和复制初始化
|
||||||
|
- explicit 修饰转换函数时,可以防止隐式转换,但按语境转换除外
|
||||||
|
|
||||||
|
|
||||||
|
代码参见:[./explict.cpp](./explicit.cpp)
|
||||||
|
|
||||||
|
参考链接:
|
||||||
|
> https://stackoverflow.com/questions/4600295/what-is-the-meaning-of-operator-bool-const
|
BIN
explicit/explict
Executable file
BIN
explicit/explict
Executable file
Binary file not shown.
46
explicit/explict.cpp
Normal file
46
explicit/explict.cpp
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
#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 b) {}
|
||||||
|
|
||||||
|
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); // 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); // 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 进行直接初始化
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user