C++ explicit

C++ explicit用来修饰构造函数,表明是显式的。与显式对应的就是隐式的,没有加explicit
修饰。隐式构造函数是可以发生隐式转换的(一个参数,或者多个参数中只有一个参数没有默认值)。

class Day{
public:
Day(int day):m_day(day){}
private:
int m_day;
};

Day a = 20;//ok,调用隐式Day(int day)隐式转换.

有时候我们不希望进行类型转换,因为自动类型转换,会丢失编译期的类型检查。
举个例子:

class Year{
public:
Year(int year):m_year(year){
}
private:
int m_year;
};

class Month{
public:
Month(int month): m_month(month){
}
private:
int m_month;
};

class Day{
public:
Day(int day):m_day(day){
}
private:
int m_day;
};

class Date
{
public:
Date(const Year &year, const Month &month, const Day& day):m_year(year),m_month(month),m_day(day){
std::cout << "Date(const Year &, const Month &,const Day &)" << std::endl;
}
~Date(void){};
private:
Year m_year;
Month m_month;
Day m_day;
};

int main(){
Date date(30,3,1985);//is ok,but the argument order is wrong
return 0;
}


我们看到Date date(30,3,1985);隐式转换失去编译器的类型检查,导致接口被误用。
所以要是我们的接口更容易使用,就需要在Year,Moth,Day的构造函数上面加上
explicit关键字。

class Year{
public:
explicit Year(int year):m_year(year){
}
private:
int m_year;
};

class Month{
public:
explicit Month(int month): m_month(month){
}
private:
int m_month;
};

class Day{
public:
explicit Day(int day):m_day(day){
}
private:
int m_day;
};

class Date
{
public:
Date(const Year &year, const Month &month, const Day& day):m_year(year),m_month(month),m_day(day){
std::cout << "Date(const Year &, const Month &,const Day &)" << std::endl;
}
~Date(void){};
private:
Year m_year;
Month m_month;
Day m_day;
};

int main(){
Date date(30,3,1985);//compile error
Date date(Year(1985),Month(3),Day(30));//ok
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值