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

程序设计基石与实践之使用构造函数初始化对象

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

预备知识

每一个类都可以提供一个构造函数,用于类对象创建时的初始化.构造函数是一种特殊的成员函数,定义时必须和类同名,这样编译器才能够将它和类的其他成员函数区分开来.构造函数各其他函数之间的一个重大差别是构造函数不能返回值,因此对它们不可以指定返回类型.通常情况下,构造函数声明为public.

UML图如下所示:

程序如下所示:

// Instantiating multiple objects of the GradeBook class and using the GradeBook constructor to specify the course name 
// when each GradeBook object is created.
#include <iostream>
using std::cout; 
using std::endl;

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

// GradeBook class definition
class GradeBook
{
public:
   // constructor initializes courseName with string supplied as argument
   GradeBook( string name )
   {
      setCourseName( name ); // call set function to initialize courseName
   } // end GradeBook constructor

   // function to set the course name
   void setCourseName( string name )
   {
      courseName = name; // store the course name in the object
   } // end function setCourseName

   // function to get the course name
   string getCourseName()
   {
      return courseName; // return object's courseName
   } // end function getCourseName

   // display a welcome message to the GradeBook user
   void displayMessage()
   {
      // call getCourseName to get the courseName
      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()
{
   // create two GradeBook objects
   GradeBook gradeBook1( "Introduction to C++ Programming" );
   GradeBook gradeBook2( "Data Structures in C++" );

   // display initial value of courseName for each GradeBook
   cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
      << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() 
      << endl;
   return 0; // indicate successful termination
} // end main

测试输出

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

抱歉!评论已关闭.