ITeye博客

C++ explicit

fuliang · 2010-09-26 23:07 · C/C++ · 编程语言 · C · C++ · C# · Markdown

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。