C++学习笔记(二十二):c++ 隐式转换与explicit关键字

  • 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;
    }

  • 15
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值