class="GradeBook.h">//GradeBook.h #include<string> using std::string; class GradeBook { public: GradeBook(string );//重载构造函数 void setCourseName(string );//设置课程名称 string getCourseName();//返回课程名称 void disPlayMessage();//欢迎信息 void determineClassAverage();//统计全班学生某一门课程的平均分以及总分 private: string courseName;//course name for this GradeBook class };
?
?
//GradeBook.cpp #include<iomanip> #include <iostream> using namespace std; #include "GradeBook.h" //两个include头文件的顺序还对报错有影响额,好神奇!!!!! GradeBook::GradeBook(string name) { setCourseName(name); } //进行判断,如果输入coursename字符大于25,则取前25个字符 void GradeBook::setCourseName(string name) { if(name.length()<=25) courseName = name; else { courseName = name.substr(0,25);//select first 25 characters cout << "Name\"" << name << "\"exceeds maximum length(25).\n" << "limiting courseName to first 25characters.\n" << endl; } } string GradeBook::getCourseName() { return courseName; } void GradeBook::disPlayMessage() { cout << "welcome to the grade book for\n" << getCourseName() << "!\n"<< endl; } void GradeBook::determineClassAverage() { int total = 0;//学生总成绩 int grade;//输入的学生成绩 int gradeCounter = 0 ;//输入的学生成绩个数 double average ;//学生的平均成绩 cout << "Enter the first grade or -1 to quit :" << endl; cin >> grade ; while(grade!=-1) { total = total +grade ; gradeCounter = gradeCounter +1 ;//计数器加一 cout << "Enter the " << gradeCounter +1<< "th grade or -1 to quit :" << endl; cin >> grade ; } if(gradeCounter != 0) { average = static_cast<double>(total)/gradeCounter ; cout << "\n Total of all " << gradeCounter << " grades entered is :" << total << endl; cout << "Class average is :" << setprecision(4) << fixed << average << endl; } else cout << "No grades were entered !" << endl; }
?
?
?
?
// main.cpp #include "GradeBook.h" int main() { GradeBook myGradeBook("C++大学基础教程"); myGradeBook.disPlayMessage(); myGradeBook.determineClassAverage(); system("pause >> cout "); return 0; }
?