您好,登錄后才能下訂單哦!
這篇文章主要講解了“怎么使用UML構(gòu)造函數(shù)初始化對象”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么使用UML構(gòu)造函數(shù)初始化對象”吧!
每一個(gè)類都可以提供一個(gè)構(gòu)造函數(shù),用于類對象創(chuàng)建時(shí)的初始化.構(gòu)造函數(shù)是一種特殊的成員函數(shù),定義時(shí)必須和類同名,這樣編譯器才能夠?qū)⑺皖惖钠渌蓡T函數(shù)區(qū)分開來.構(gòu)造函數(shù)各其他函數(shù)之間的一個(gè)重大差別是構(gòu)造函數(shù)不能返回值,因此對它們不可以指定返回類型.通常情況下,構(gòu)造函數(shù)聲明為public.
// Instantiating multiple objects of the GradeBook class and using the GradeBook constructor to specify the course name // when each GradeBook object is created. #include <iostream> using std::cout; using std::endl; #include <string> // program uses C++ standard string class using std::string; // GradeBook class definition class GradeBook { public: // constructor initializes courseName with string supplied as argument GradeBook( string name ) { setCourseName( name ); // call set function to initialize courseName } // end GradeBook constructor // function to set the course name void setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName // function to get the course name string getCourseName() { return courseName; // return object's courseName } // end function getCourseName // display a welcome message to the GradeBook user void displayMessage() { // call getCourseName to get the courseName cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessage private: string courseName; // course name for this GradeBook }; // end class GradeBook // function main begins program execution int main() { // create two GradeBook objects GradeBook gradeBook1( "Introduction to C++ Programming" ); GradeBook gradeBook2( "Data Structures in C++" ); // display initial value of courseName for each GradeBook cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() << endl; return 0; // indicate successful termination } // end main
感謝各位的閱讀,以上就是“怎么使用UML構(gòu)造函數(shù)初始化對象”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對怎么使用UML構(gòu)造函數(shù)初始化對象這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。