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