按如下要求修改GradeBook类:
a)包括第二个 string 数据成员,它表示授课教师的名字。
b)提供一个可以改变教师姓名的设置函数,以及一个可以得到该名字的获取函数。
c)修改构造函数,它指定了两个形参,一个针对课程名称,另一个针对教师姓名。
d)修splayessage使得它首先输出信息和课程名称,然后输出“Thiscourse is presented by:”,后跟教师姓名。
第一种情况:命名一个GradeBook.h文件
以下文件为GradeBook.h文件,不可以直接运行。
//3.11修改GradeBook类
#include <iostream>
#include <string>
// using namespace std;单独的类文件,不能使用using命令class GradeBook
{
public:GradeBook(std::string course_name, std::string teacher_name)//构造函数{setCourseName(course_name);setCourseTeacher(teacher_name);}void setCourseName(std::string name){if (name.size() <= 25)courseName = name;if (name.size() > 25){courseName = name.substr(0, 25);std::cerr << "name\"" << name << "\"exceeds maximum length(25).\n"<< "Limiting courseName to first 25 characters.\n"<< std::endl;}}std::string getCourseName() const{return courseName;}void setCourseTeacher(std::string name){courseTeacher = name;}std::string getCourseTeacher() const{return courseTeacher;}void displayMessage() const{std::cout << "Welcome eto the grade book for\n"<< getCourseName() << "!\nThis course is presented by "<< getCourseTeacher() << std::endl;}private:std::string courseName, courseTeacher;
};
第二种情况:采用GradeBook.h和GradeBook.cpp两个文件
1.头文件GradeBook.h用于描述类的公共接口不暴露类的成员函数的实现。(给客户提供他需要输入的信息,但看不到具体实现过程)
2.GradeBook.cpp中GradeBook成员函数的定义描述了GradeBook类的具体实现细节。(类实现程序员编写的)
// GradeBook.h#include <iostream>
#include <string>class GradeBook
{
public:GradeBook(std::string, std::string);void setCourseName(std::string);std::string getCourseName() const;void setCourseTeacher(std::string);std::string getCourseTeacher() const;void displayMessage() const;private:std::string courseName, courseTeacher;
};
//GradeBook.cpp#include <iostream>
#include "GradeBook.h"
using namespace std;GradeBook::GradeBook(string course_name, string teacher_name){setCourseName(course_name);setCourseTeacher(teacher_name);}void GradeBook::setCourseName(string course_name){if (course_name.size() <= 25)courseName = course_name;if (course_name.size() > 25){courseName = course_name.substr(0, 25);cerr << "name\"" << course_name << "\"exceeds maximum length(25).\n"<< "Limiting courseName to first 25 characters.\n"<< endl;}}
string GradeBook::getCourseName() const{return courseName;}void GradeBook::setCourseTeacher(string teacher_name){courseTeacher = teacher_name;}
string GradeBook::getCourseTeacher() const{return courseTeacher;}void GradeBook::displayMessage() const{cout << "Welcome eto the grade book for\n"<< getCourseName() << "!\nThis course is presented by "<< getCourseTeacher() << endl;}