C++的隐式或显式转换
作者:互联网
隐式转换
- 数字之间的隐式转换,要注意的是不能超出类型范围
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();
}
- 参数传递,对象创建时也有隐式转换,但要注意隐式转换只能自动转换一次,所以字符串字面值(如“zimianzhi”)不能隐式转换成对象传给参数,因为字符串本质上是char Array,要先转换成字符串,再转成对象,转换了两次。
#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
不加限制时,可自由选择是隐式转换还是显式转换,但将类的构造器用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) {}
};
标签:Name,int,Age,C++,Entity,显式,隐式,name 来源: https://blog.csdn.net/weixin_44078014/article/details/122693002