C++使用初始化列表的方式来初始化字段的方法
几个月之前,接触Androidrecovery源代码的时候,看ScreenRecoveryUI类的时候,那时候C++基础还不是特别好,一直不明白以下的初始化方式:
下面这个是Recovery的一个构造函数,代码位于:screen_ui.cpp,它的类的实现在screen_ui.h。
如下这个ScreenRecoveryUI类,这个类是继承于RecoveryUI类的:
这个文件在screen_ui.h
classScreenRecoveryUI:publicRecoveryUI{
public:
ScreenRecoveryUI();
voidInit();
voidSetLocale(constchar*locale);
//overallrecoverystate("backgroundimage")
voidSetBackground(Iconicon);
//progressindicator
voidSetProgressType(ProgressTypetype);
voidShowProgress(floatportion,floatseconds);
voidSetProgress(floatfraction);
voidSetStage(intcurrent,intmax);
//textlog
voidShowText(boolvisible);
boolIsTextVisible();
boolWasTextEverVisible();
//printingmessages
voidPrint(constchar*fmt,...)__printflike(2,3);
voidShowFile(constchar*filename);
//menudisplay
voidStartMenu(constchar*const*headers,constchar*const*items,
intinitial_selection);
intSelectMenu(intsel);
voidEndMenu();
voidKeyLongPress(int);
voidRedraw();
enumUIElement{
HEADER,MENU,MENU_SEL_BG,MENU_SEL_BG_ACTIVE,MENU_SEL_FG,LOG,TEXT_FILL,INFO
};
voidSetColor(UIElemente);
private:
IconcurrentIcon;
intinstallingFrame;
constchar*locale;
boolrtl_locale;
pthread_mutex_tupdateMutex;
GRSurface*backgroundIcon[5];
GRSurface*backgroundText[5];
GRSurface**installation;
GRSurface*progressBarEmpty;
GRSurface*progressBarFill;
GRSurface*stageMarkerEmpty;
GRSurface*stageMarkerFill;
ProgressTypeprogressBarType;
floatprogressScopeStart,progressScopeSize,progress;
doubleprogressScopeTime,progressScopeDuration;
//truewhenbothgraphicspagesarethesame(exceptfortheprogressbar).
boolpagesIdentical;
size_ttext_cols_,text_rows_;
//Logtextoverlay,displayedwhenamagickeyispressed.
char**text_;
size_ttext_col_,text_row_,text_top_;
boolshow_text;
boolshow_text_ever;//hasshow_texteverbeentrue?
char**menu_;
constchar*const*menu_headers_;
boolshow_menu;
intmenu_items,menu_sel;
//Analternatetextscreen,swappedwith'text_'whenwe'reviewingalogfile.
char**file_viewer_text_;
pthread_tprogress_thread_;
intanimation_fps;
intinstalling_frames;
inticonX,iconY;
intstage,max_stage;
voiddraw_background_locked(Iconicon);
voiddraw_progress_locked();
voiddraw_screen_locked();
voidupdate_screen_locked();
voidupdate_progress_locked();
staticvoid*ProgressThreadStartRoutine(void*data);
voidProgressThreadLoop();
voidShowFile(FILE*);
voidPutChar(char);
voidClearText();
voidDrawHorizontalRule(int*y);
voidDrawTextLine(int*y,constchar*line,boolbold);
voidDrawTextLines(int*y,constchar*const*lines);
voidLoadBitmap(constchar*filename,GRSurface**surface);
voidLoadBitmapArray(constchar*filename,int*frames,GRSurface***surface);
voidLoadLocalizedBitmap(constchar*filename,GRSurface**surface);
};
下面是这个类的构造函数的实现,其中构造函数就采用了初始化列表的方式来初始化字段,以下构造函数的实现在screen_ui.cpp文件中可以找到。
ScreenRecoveryUI::ScreenRecoveryUI():
currentIcon(NONE),
installingFrame(0),
locale(nullptr),
rtl_locale(false),
progressBarType(EMPTY),
progressScopeStart(0),
progressScopeSize(0),
progress(0),
pagesIdentical(false),
text_cols_(0),
text_rows_(0),
text_(nullptr),
text_col_(0),
text_row_(0),
text_top_(0),
show_text(false),
show_text_ever(false),
menu_(nullptr),
show_menu(false),
menu_items(0),
menu_sel(0),
file_viewer_text_(nullptr),
animation_fps(20),
installing_frames(-1),
stage(-1),
max_stage(-1){
for(inti=0;i<5;i++){
backgroundIcon[i]=nullptr;
}
pthread_mutex_init(&updateMutex,nullptr);
}
可以来看看RecoveryUI类:
在ui.h中:
classRecoveryUI{
public:
RecoveryUI();
virtual~RecoveryUI(){}
//Initializetheobject;calledbeforeanythingelse.
virtualvoidInit();
//Showastageindicator.CallimmediatelyafterInit().
virtualvoidSetStage(intcurrent,intmax)=0;
//AftercallingInit(),youcantelltheUIwhatlocaleitisoperatingin.
virtualvoidSetLocale(constchar*locale)=0;
//Settheoverallrecoverystate("backgroundimage").
enumIcon{NONE,INSTALLING_UPDATE,ERASING,NO_COMMAND,ERROR};
virtualvoidSetBackground(Iconicon)=0;
//---progressindicator---
enumProgressType{EMPTY,INDETERMINATE,DETERMINATE};
virtualvoidSetProgressType(ProgressTypedeterminate)=0;
//Showaprogressbaranddefinethescopeofthenextoperation:
//portion-fractionoftheprogressbarthenextoperationwilluse
//seconds-expectedtimeinterval(progressbarmovesatthisminimumrate)
virtualvoidShowProgress(floatportion,floatseconds)=0;
//Setprogressbarposition(0.0-1.0withinthescopedefined
//bythelastcalltoShowProgress).
virtualvoidSetProgress(floatfraction)=0;
//---textlog---
virtualvoidShowText(boolvisible)=0;
virtualboolIsTextVisible()=0;
virtualboolWasTextEverVisible()=0;
//Writeamessagetotheon-screenlog(showniftheuserhas
//toggledonthetextdisplay).
virtualvoidPrint(constchar*fmt,...)__printflike(2,3)=0;
virtualvoidShowFile(constchar*filename)=0;
//---keyhandling---
//Waitforakeyandreturnit.Mayreturn-1aftertimeout.
virtualintWaitKey();
virtualboolIsKeyPressed(intkey);
virtualboolIsLongPress();
//Returnstrueifyouhavethevolumeup/downandpowertriotypical
//ofphonesandtablets,falseotherwise.
virtualboolHasThreeButtons();
//Eraseanyqueued-upkeys.
virtualvoidFlushKeys();
//Calledoneachkeypress,evenwhileoperationsareinprogress.
//Returnvalueindicateswhetheranimmediateoperationshouldbe
//triggered(togglingthedisplay,rebootingthedevice),orif
//thekeyshouldbeenqueuedforusebythemainthread.
enumKeyAction{ENQUEUE,TOGGLE,REBOOT,IGNORE};
virtualKeyActionCheckKey(intkey,boolis_long_press);
//Calledwhenakeyishelddownlongenoughtohavebeena
//long-press(butbeforethekeyisreleased).Thismeansthat
//ifthekeyiseventuallyregistered(releasedwithoutanyother
//keysbeingpressedinthemeantime),CheckKeywillbecalledwith
//'is_long_press'true.
virtualvoidKeyLongPress(intkey);
//Normallyinrecoverythere'sakeysequencethattriggers
//immediaterebootofthedevice,regardlessofwhatrecoveryis
//doing(withthedefaultCheckKeyimplementation,it'spressing
//thepowerbutton7timesinrow).Callthistoenableor
//disablethatfeature.Itisenabledbydefault.
virtualvoidSetEnableReboot(boolenabled);
//---menudisplay---
//Displaysomeheadertextfollowedbyamenuofitems,whichappears
//atthetopofthescreen(inplaceofanyscrollingui_print()
//output,ifnecessary).
virtualvoidStartMenu(constchar*const*headers,constchar*const*items,
intinitial_selection)=0;
//Setthemenuhighlighttothegivenindex,wrappingifnecessary.
//Returnstheactualitemselected.
virtualintSelectMenu(intsel)=0;
//Endmenumode,resettingthetextoverlaysothatui_print()
//statementswillbedisplayed.
virtualvoidEndMenu()=0;
protected:
voidEnqueueKey(intkey_code);
private:
//Keyeventinputqueue
pthread_mutex_tkey_queue_mutex;
pthread_cond_tkey_queue_cond;
intkey_queue[256],key_queue_len;
charkey_pressed[KEY_MAX+1];//underkey_queue_mutex
intkey_last_down;//underkey_queue_mutex
boolkey_long_press;//underkey_queue_mutex
intkey_down_count;//underkey_queue_mutex
boolenable_reboot;//underkey_queue_mutex
intrel_sum;
intconsecutive_power_keys;
intlast_key;
boolhas_power_key;
boolhas_up_key;
boolhas_down_key;
structkey_timer_t{
RecoveryUI*ui;
intkey_code;
intcount;
};
pthread_tinput_thread_;
voidOnKeyDetected(intkey_code);
staticintInputCallback(intfd,uint32_tepevents,void*data);
intOnInputEvent(intfd,uint32_tepevents);
voidProcessKey(intkey_code,intupdown);
boolIsUsbConnected();
staticvoid*time_key_helper(void*cookie);
voidtime_key(intkey_code,intcount);
};
ui.cpp中,也是采用字段初始化的方式来实现构造函数:
RecoveryUI::RecoveryUI()
:key_queue_len(0),
key_last_down(-1),
key_long_press(false),
key_down_count(0),
enable_reboot(true),
consecutive_power_keys(0),
last_key(-1),
has_power_key(false),
has_up_key(false),
has_down_key(false){
pthread_mutex_init(&key_queue_mutex,nullptr);
pthread_cond_init(&key_queue_cond,nullptr);
memset(key_pressed,0,sizeof(key_pressed));
}
现在看明白了。
写一个测试案例看看就懂了,果然一例解千愁啊!
#includeusingnamespacestd; classScreenRecoveryUI { private: intr,g,b; charbuffer[10]; char*p; public: ScreenRecoveryUI(); voidsetvalue(inta,intb,intc); voidprint(); }; //使用初始化列表的方式初始化构造函数里的私有环境变量 ScreenRecoveryUI::ScreenRecoveryUI(): r(0), g(0), b(0), p(nullptr){ for(inti=0;i<10;i++){ buffer[i]=0; } } voidScreenRecoveryUI::setvalue(inta,intb,intc) { this->r=a; this->g=b; this->b=c; } voidScreenRecoveryUI::print() { cout<<"r:"< r< g< 运行结果:
r:255
g:255
b:0总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接