10~C++ explicit

09~C++类型转换 一节列举了显式类型转换和隐式类型转换的几种方式;
但是读者应当意识到:隐式类型转换未必总是安全的。
为了解决隐式类型转换的安全问题,C++提供了explicit 关键字用来声明—该类型转换函数必须使用显式类型转换的方式调用,也就是强调程序员清楚的知道自己在做什么,否则不允许编译

应当注意:只有构造函数或者类型转换函数可以使用explicit修饰

#include <iostream>
using namespace std;
struct Stack {
	explicit Stack(void) {
		cout <<  "构造函数" << endl;
	}
	explicit Stack(int a ) {
		cout <<  "int->Stack 类型转换" << endl;
	}
	explicit Stack(double b) {
		cout << "double->Stack 类型转换" << endl;
	}
	//拷贝构造函数 原则上是没必要使用explicit 声明的
	Stack(Stack& that) {
		cout << "非常引用 拷贝构造函数" << endl;
	}
	Stack(Stack const& that) {
		cout << "常引用 拷贝构造函数" << endl;
	}
	Stack& operator= (Stack const& that) {
		cout <<"赋值函数" <<endl;
	}
};

void fool(Stack i)
{	
}

Stack barn(void)
{
	/*隐式类型转换,编译出错*/
	//return 3.3;
	/*显式类型转换 ok*/
	return Stack(3.3);
}


int main(void) {
/*缺省构造 使用了explicit无所谓*/
Stack s1;
Stack s2;

/*int -> Stack 类型隐式转,编译出错*/
//s1  = 1;
/*显示类型转换 int-> Stack*/
/*显式类型转换 ok*/
s1 = Stack(1);

/*int->Stack 类型转换,编译出错*/
//fool(1);
/*显式类型转换 ok*/
fool(Stack(1));

return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值