include <iostream> int main() { int TypeInt = 3; short TypeShort = TypeInt; char TypeChar = TypeInt; double TypeDouble = TypeInt; float TypeFloat = TypeInt; std::cout << sizeof(TypeInt) << std::endl; std::cout << sizeof(TypeShort) << std::endl; std::cout << sizeof(TypeChar) << std::endl; std::cout << sizeof(TypeDouble) << std::endl; std::cout << sizeof(TypeFloat) << std::endl; std::cin.get(); }
#include <iostream> #include <string> using String = std::string; class Entity { private: int Age; String Name; public: Entity(int age) : Age(age), Name("Unknown") {} Entity(String name) : Age(-1), Name(name) {} Entity(int age, String name) : Age(age), Name(name) {} }; void PrintEntity(const Entity& entity) { // } int main() { PrintEntity(22); //隐式转换 PrintEntity(std::string("hello,world")); std::cin.get(); }
不加限制时,可自由选择是隐式转换还是显式转换,但将类的构造器用explicit修饰后,隐式转换失效,只能显式转换。
class Entity { private: int Age; String Name; public: explicit Entity(int age) : Age(age), Name("Unknown") {} Entity(String name) : Age(-1), Name(name) {} Entity(int age, String name) : Age(age), Name(name) {} };