关于C++中的explicit关键字
在C++中,explicit关键字是用来修饰类的构造函数的。含有被该关键字修饰过的构造函数的类,
将不能进行隐式类型转换,类型转换只能显式进行。并且需要注意的是该关键字仅用于类内的构造函数的声明上。
例如:
#include <iostream>
class Ball
{
public:
Ball(double r):R(r){}
Ball(int x=0,int y=0,int z=0): X(x),Y(y),Z(z){}
Ball( Ball& B):R(B.getR()),X(B.getX()),Y(B.getY()),Z(B.getZ()){}
~Ball(){}
double getR(){return this->R;}
int getX(){return this->X;}
int getY(){return this->Y;}
int getZ(){return this->Z;}
private:
double R; // 半径
int X,Y,Z; // 球心空间三维坐标
};
class Ball2 // 使用explicit关键字修饰构造
{
public:
explicit Ball2(double r):R(r){}
explicit Ball2(int x=0,int y=0,int z=0,double r=0.0):X(x),Y(y),Z(z),R(r){}
explicit Ball2( Ball& B):R(B.getR()),X(B.getX()),Y(B.getY()),Z(B.getZ()){}
~Ball2(){}
double getR(){return this->R;}
int getX(){return this->X;}
int getY(){return this->Y;}
int getZ(){return this->Z;}
private:
double R; // 半径
int X,Y,Z; // 球心空间三维坐标
};
int main(void)
{
//在未使用关键字explicit修饰是,会存在不少的隐式转换
Ball a = {1.2}; //这段代码是成立的
//这里含有一个隐式的转换
//temp =Ball{1.2}; Ball a{temp};
Ball b = {12}; //这里同样的也包含了隐式转换
// Ball2就可以避免这种隐式转换了
Ball2 a2{1.2};
Ball2 b2{12};
// 还用一种比较容易出现的问题,涉及到之前的元素初始化方式的不统一
// 下面的这段代码是非常容易出错的,这种写法是错误的
//Ball2 c = {12};
return 0;
}