编程语言
首页 > 编程语言> > C++的隐式或显式转换

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();
}
#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