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

程序设计基石与实践之定义具有成员函数的类

2019年03月19日 编程语言 ⁄ 共 2055字 ⁄ 字号 评论关闭

现在从一个由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 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类,它的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

测试结果

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

抱歉!评论已关闭.