您的位置:首页 > 编程语言 > C语言/C++

explicit&用法&作用

2016-04-04 19:08 225 查看
/*
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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 对象 class 函数