现在的位置: 首页 > 编程语言 > 正文

程序设计基石与实践之数据成员与set和get函数 程序设计基石与实践之

2019年03月19日 编程语言 ⁄ 共 1650字 ⁄ 字号 评论关闭
文章目录

在博文<<程序设计基石与实践之定义具有成员函数的类 >>介绍了GradeBook类表示可供教师管理学生考试成绩的成绩簿,在本博介结具有一个数据成员,一个Set函数和一个 Get函数的GradeBook类 .而UML图如下所示:

参考程序

// Define class GradeBook that contains a courseName data member
// and member functions to set and get its value; 
// Create and manipulate a GradeBook object.
#include <iostream>
using std::cout; 
using std::cin;
using std::endl;

#include <string> // program uses C++ standard string class
using std::string;
using std::getline;

// GradeBook class definition
class GradeBook
{
public:
   // function that sets the course name
   void setCourseName( string name )
   {      
      courseName = name; // store the course name in the object
   } // end function setCourseName
   
   // function that gets the course name
   string getCourseName() 
   {
      return courseName; // return the object's courseName
   } // end function getCourseName

   // function that displays a welcome message
   void displayMessage()
   {
      // this statement calls getCourseName to get the 
      // name of the course this GradeBook represents
      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()
{
   string nameOfCourse; // string of characters to store the course name
   GradeBook myGradeBook; // create a GradeBook object named myGradeBook
   
   // display initial value of courseName
   cout << "Initial course name is: " << myGradeBook.getCourseName() 
      << endl;

   // prompt for, input and set course name
   cout << "\nPlease enter the course name:" << endl;
   getline( cin, nameOfCourse ); // read a course name with blanks
   myGradeBook.setCourseName( nameOfCourse ); // set the course name

   cout << endl; // outputs a blank line
   myGradeBook.displayMessage(); // display message with new course name
   return 0; // indicate successful termination
} // end main

输出结果

关于Program Language更多讨论与交流,敬请关注本博客和新浪微博songzi_tea.

抱歉!评论已关闭.