C++11新特性- 委托構(gòu)造函數(shù)
C++11之前的狀況
構(gòu)造函數(shù)多了以后,幾乎必然地會出現(xiàn)代碼重復(fù)的情況,為了避免這種情況,往往需要另外編寫一個初始化函數(shù)。例如下面的Rect類:
struct?Point{
????int?x;
????int?y;
};struct?Rect{
????Rect(){
????????init(0,?0,?0,?0,?0,?0);
????}
????Rect(int?l,?int?t,?int?r,?int?b){
????????init(l,?t,?r,?b,?lc,?fc,?0,?0);
????}
????Rect(int?l,?int?t,?int?r,?int?b,?
??????????int?lc,?int?fc){
????????init(l,?t,?r,?b,?lc,?fc);
????}
????Rect(Point?topleft,?Point?bottomright){
????????init(topleft.x,?topleft.y,?
????????bottomright.x,?bottomright.y,
????????0,?0);
????}
????init(int?l,?int?t,?int?r,?int?b,?
??????????int?lc,?int?fc){
????????left?=?l;?top?=?t;????????
????????right?=?r;?bottom?=?b;
????????line_color?=?lc;
????????fill_color?=?fc;
????????//do?something?else...
????}
????int?left;
????int?top;
????int?right;
????int?bottom;
????int?line_color;?
????int?fill_color;????
};數(shù)據(jù)成員初始化之后要進行某些其他的工作,而這些工作又是每種構(gòu)造方式都必須的,所以另外準(zhǔn)備了一個init函數(shù)供各個構(gòu)造函數(shù)調(diào)用。
這種方式確實避免了代碼重復(fù),但是有兩個問題:
沒有辦法不重復(fù)地使用成員初始化列表
必須另外編寫一個初始化函數(shù)。
C++11的解決方案
C++11擴展了構(gòu)造函數(shù)的功能,增加了委托構(gòu)造函數(shù)的概念,使得一個構(gòu)造函數(shù)可以委托其他構(gòu)造函數(shù)完成工作。使用委托構(gòu)造函數(shù)以后,前面的代碼變成下面這樣:
struct?Point{
????int?x;
????int?y;
};
struct?Rect{
????Rect()
????????:Rect(0,?0,?0,?0,?0,?0)
????{
????}
????Rect(int?l,?int?t,?int?r,?int?b)
????????:Rect(l,?t,?r,?b,?0,?0)
????{
????}
????Rect(Point?topleft,?Point?bottomright)
????????:Rect(topleft.x,?topleft.y,
?????????????bottomright.x,?bottomright.y,
?????????????0,?0)
????{
????}
????Rect(int?l,?int?t,?int?r,?int?b,
?????????int?lc,?int?fc)
????????:left(l),?top(t),?right(r),bottom(b),
??????????line_color(lc),?fill_color(fc)
????{
????????//do?something?else...
????}
????int?left;
????int?top;
????int?right;
????int?bottom;
????int?line_color;
????int?fill_color;};
真正的構(gòu)造工作由最后一個構(gòu)造函數(shù)完成,而其他的構(gòu)造函數(shù)都是委托最后一個構(gòu)造函數(shù)完成各自的構(gòu)造工作。這樣即去掉了重復(fù)代碼又避免了前一種方法帶來的問題。
通過代碼可以看出:委托構(gòu)造函數(shù)的語法和構(gòu)造函數(shù)中調(diào)用基類構(gòu)造函數(shù)一樣。調(diào)用順序,效果什么也差不多。
作者觀點
DRY(Don't repeat yourself )也需要開發(fā)環(huán)境的支持。





