c++中的隐式构造函数
在c++中允许编译器进行一次隐式转换 ,即将一个数据类型转化为另一个数据类型来用。像基础的char命名的用整数赋值会转化为asc码来显示,相当于一次隐形转化。而在类的构造函数中我们也可以使用这种隐式转化来构造实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Example { private : int m_age; std::string m_name; public : Example (const std::string name) :m_age (-1 ),m_name (name){} Example (int age) :m_age (age),m_name ("Unknow" ){} }; void Print (const Example& e) { stdL::cout << e. } int main () { Example a=21 ; Print (22 ); Example b="LYsnowQ" ; Print ("LYsnowQ" ); Print (std::string ("LYsnowQ" )); Example b=std::string ("LYsnowQ" ); Print (Example ("LYsnowQ" )); }
explicit关键字
在上述的隐式转换中,编译器可以帮我们进项隐式转化,但是有时候我们像禁用编译器的转化,以防止代码出现差错,呢么explicit关键字就是禁用编译器的隐式编译器的代码转化,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Example { private : int m_age; std::string m_name; public : explicit Example (const std::string name) :m_age(-1 ),m_name(name){ } explicit Example (int age) :m_age(age),m_name("Unknow" ){ } }; void Print (const Example& e) { stdL::cout << e. } int main () { Example a=21 ; Print (22 ); Example a (Example(21 )) ; Print (Example ("LYsnowQ" )); Example a = Example (21 ); a = Example ("LYsnowQ" ); }
资料参考:
youtube上the cherno的cpp系列教学