GradeBook类怎么定义

发布时间:2022-04-06 16:21:38 作者:iii
来源:亿速云 阅读:282

这篇文章主要讲解了“GradeBook类怎么定义”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“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 definition
class 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 execution
int main()
{
   GradeBook myGradeBook; // create a GradeBook object named myGradeBook
   myGradeBook.displayMessage(); // call object's displayMessage function	
   return 0; // indicate successful termination
} // end main

测试结果

GradeBook类怎么定义

定义具有参数的成员函数

在这里,我们重新定义了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 class
using std::string;
using std::getline;

// GradeBook class definition
class 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 execution
int 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

感谢各位的阅读,以上就是“GradeBook类怎么定义”的内容了,经过本文的学习后,相信大家对GradeBook类怎么定义这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. python类如何定义
  2. python怎样定义类

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:怎么使用UML构造函数初始化对象

下一篇:PHP多态性和虚函数实例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》