explicit&用法&作用

/*
explicit:
1,使用在一个参数的构造函数
2,使用之后该类的对象只能显示的调用构造函数 不能发生隐式的类型转换
*/

// eg:

#include <iostream>

using namespace std;

class test1 //未使用explicit
{
private:
	double a;
	int b;
public:
	test1(int b_);
	test1(double a_, int b_ = 0);
};

class test2 //使用explicit
{
private:
	double a;
	int b;
public:
	explicit test2(int b_);
	explicit test2(double a_, int b_ = 0);
};

test1::test1(int b_):b(b_)
{
cout << "警告!\a正在使用构造函数1\n";
}
test1::test1(double a_, int b_):a(a_),b(b_)
{
cout << "警告!\a正在使用构造函数2\n";
}

test2::test2(int b_):b(b_)
{
cout << "警告!\a正在使用构造函数3\n";
}
test2::test2(double a_, int b_):a(a_),b(b_)
{
cout << "警告!\a正在使用构造函数4\n";
}

void main()
{
	//未使用explicit
	test1 one(2);
	one = 3; //本来不该使用构造函数的  但是确实是调用了 且不易被察觉(当然这里为了试验在构造函数里给出了提示 容易被发现)

	//使用explicit
	test2 two(3.6);
  // two = 3.4;     //错误	1	error C2679: 二进制“=”: 没有找到接受“double”类型的右操作数的运算符(或没有可接受的转换)


	system("pause");
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值