- c++允许编译器对代码执行一次隐式转换。
-
#include<iostream> #include<string> class Entity { public: std::string name; int age; Entity(int x) { age = x; } Entity(std::string x) { name = x; } }; void PrintEntity(Entity e) { std::cout << e.age << ":" << e.name << std::endl; } int main() { PrintEntity(20); //隐式转换,调用Entity(int x)构造函数将20隐式转换为Entity对象 PrintEntity(std::string("pcop")); //隐式转换,调用Entity(std::string x)构造函数将"20"pcop"隐式转换为Entity对象 std::cin.get(); return 0; }
-
#include<iostream> #include<string> class Entity { public: std::string name; int age; Entity(int x) { age = x; } Entity(std::string x) { name = x; } }; void PrintEntity(Entity e) { std::cout << e.age << ":" << e.name << std::endl; } int main() { PrintEntity(20); //隐式转换,调用Entity(int x)构造函数将20隐式转换为Entity对象 PrintEntity(std::string("pcop")); //隐式转换,调用Entity(std::string x)构造函数将"20"pcop"隐式转换为Entity对象 PrintEntity("pcop"); //报错,因为pcop时const char*类型的,编译器调用隐式转换将时const char*类型转换为string,但仅能隐式转换一次,故编译器不能将string类型隐式转换为Entity类型 std::cin.get(); return 0; }
-
explicit关键字放在构造函数前面,意味着该构造函数不允许进行隐式转换。示例如下:
-
#include<iostream> #include<string> class Entity { public: std::string name; int age; explicit Entity(int x) { age = x; } Entity(std::string x) { name = x; } }; void PrintEntity(Entity e) { std::cout << e.age << ":" << e.name << std::endl; } int main() { PrintEntity(20); //不能进行隐式转换,因为调用Entity(int x)构造函数前面有explicit关键字 PrintEntity(std::string("pcop")); //隐式转换,调用Entity(std::string x)构造函数将"20"pcop"隐式转换为Entity对象 std::cin.get(); return 0; }
C++学习笔记(二十二):c++ 隐式转换与explicit关键字
于 2024-01-03 13:53:36 首次发布