千家信息网

如何理解set和get函数

发表于:2025-11-14 作者:千家信息网编辑
千家信息网最后更新 2025年11月14日,如何理解set和get函数,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。文章目录输出结果一个Set函数和一个 Get函数的GradeBo
千家信息网最后更新 2025年11月14日如何理解set和get函数

如何理解set和get函数,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

文章目录

  • 输出结果

一个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 using std::cout; using std::cin;using std::endl;#include  // program uses C++ standard string classusing std::string;using std::getline;// GradeBook class definitionclass 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 displayMessageprivate:   string courseName; // course name for this GradeBook}; // 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      // 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
输出结果

看完上述内容,你们掌握如何理解set和get函数的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

0