程式實踐:使用建構函式初始化對象,建構函式初始化

來源:互聯網
上載者:User

程式實踐:使用建構函式初始化對象,建構函式初始化
預備知識

每一個類都可以提供一個建構函式,用於類對象建立時的初始化.建構函式是一種特殊的成員函數,定義時必須和類同名,這樣編譯器才能夠將它和類的其他成員函數區分開來.建構函式各其他函數之間的一個重大差別是建構函式不能傳回值,因此對它們不可以指定傳回型別.通常情況下,建構函式聲明為public.

UML圖如下所示:


程式如下所示:

// 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 classusing std::string;// GradeBook class definitionclass 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 displayMessageprivate:   string courseName; // course name for this GradeBook}; // end class GradeBook  // function main begins program executionint 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
測試輸出



關於Program Language更多討論與交流,敬請關注本部落格和新浪微博songzi_tea.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.