程式實踐:定義具有成員函數的類,成員函數
現在從一個由GradeBook類和main函數組成的例子說起,此例是一系例循序漸進例子中的第一個,這些例子通過後續博文講解,最終是一個功能眾多的GradeBook類.
定義具有無參數的成員函數
這裡,GradeBook類表示可供教師管理學生考試成績的成績表,而在main函數建立了一個GradeBook對象.main函數使用這個對象和它的成員函數,在螢幕上顯示一條歡迎教師進入成績表程式的資訊.
PS:關鍵字class後跟類名GradeBook.按照慣例,使用者定義的類名字以大寫字母開頭,而且為了增強可讀性,類名中每個隨後的單詞其首字母也為大寫.同時,每個類的體包圍在一對花括弧中({和}).類的定義以分號結束.
// Define class GradeBook with a member function displayMessage;// Create a GradeBook object and call its displayMessage function.#include <iostream>using std::cout;using std::endl;// GradeBook class definitionclass GradeBook{public: // function that displays a welcome message to the GradeBook user void displayMessage() { cout << "Welcome to the Grade Book!" << endl; } // end function displayMessage}; // end class GradeBook // function main begins program executionint main(){ GradeBook myGradeBook; // create a GradeBook object named myGradeBook myGradeBook.displayMessage(); // call object's displayMessage function return 0; // indicate successful termination} // end main測試結果
定義具有參數的成員函數
在這裡,我們重新定義了GradeBook類,它的displayMessage成員函數將課程名稱作為歡迎訊息的一部分,這個新的成員函數displayMessage規定了一個表示要輸出的課程名稱的形參.
// Define class GradeBook with a member function that takes a parameter;// Create a GradeBook object and call its displayMessage function.#include <iostream>using std::cout; using std::cin;using std::endl;#include <string> // program uses C++ standard string classusing std::string;using std::getline;// GradeBook class definitionclass GradeBook{public: // function that displays a welcome message to the GradeBook user void displayMessage( string courseName ) { cout << "Welcome to the grade book for\n" << courseName << "!" << endl; } // end function displayMessage}; // end class GradeBook // function main begins program executionint main(){ string nameOfCourse; // string of characters to store the course name GradeBook myGradeBook; // create a GradeBook object named myGradeBook // prompt for and input course name cout << "Please enter the course name:" << endl; getline( cin, nameOfCourse ); // read a course name with blanks cout << endl; // output a blank line // call myGradeBook's displayMessage function // and pass nameOfCourse as an argument myGradeBook.displayMessage( nameOfCourse ); return 0; // indicate successful termination} // end main測試結果
關於Program Language更多討論與交流,敬請關注本部落格和新浪微博songzi_tea.