/*
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");
}
explicit&用法&作用
最新推荐文章于 2024-07-22 15:16:43 发布