实验4 类的组合继承模板类标准库
实验任务二
gradecalc.hpp
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 #include <algorithm> 5 #include <numeric> 6 #include <iomanip> 7 8 using std::vector; 9 using std::string; 10 using std::cin; 11 using std::cout; 12 using std::endl; 13 14 class GradeCalc: public vector<int> { 15 public: 16 GradeCalc(const string &cname, int size); 17 void input(); // 录入成绩 18 void output() const; // 输出成绩 19 void sort(bool ascending = false); // 排序 (默认降序) 20 int min() const; // 返回最低分 21 int max() const; // 返回最高分 22 float average() const; // 返回平均分 23 void info(); // 输出课程成绩信息 24 25 private: 26 void compute(); // 成绩统计 27 28 private: 29 string course_name; // 课程名 30 int n; // 课程人数 31 vector<int> counts = vector<int>(5, 0); // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] 32 vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 33 }; 34 35 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {} 36 37 void GradeCalc::input() { 38 int grade; 39 40 for(int i = 0; i < n; ++i) { 41 cin >> grade; 42 this->push_back(grade); 43 } 44 } 45 46 void GradeCalc::output() const { 47 for(auto ptr = this->begin(); ptr != this->end(); ++ptr) 48 cout << *ptr << " "; 49 cout << endl; 50 } 51 52 void GradeCalc::sort(bool ascending) { 53 if(ascending) 54 std::sort(this->begin(), this->end()); 55 else 56 std::sort(this->begin(), this->end(), std::greater<int>()); 57 } 58 59 int GradeCalc::min() const { 60 return *std::min_element(this->begin(), this->end()); 61 } 62 63 int GradeCalc::max() const { 64 return *std::max_element(this->begin(), this->end()); 65 } 66 67 float GradeCalc::average() const { 68 return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n; 69 } 70 71 void GradeCalc::compute() { 72 for(int grade: *this) { 73 if(grade < 60) 74 counts.at(0)++; 75 else if(grade >= 60 && grade < 70) 76 counts.at(1)++; 77 else if(grade >= 70 && grade < 80) 78 counts.at(2)++; 79 else if(grade >= 80 && grade < 90) 80 counts.at(3)++; 81 else if(grade >= 90) 82 counts.at(4)++; 83 } 84 85 for(int i = 0; i < rates.size(); ++i) 86 rates.at(i) = counts.at(i) * 1.0 / n; 87 } 88 89 void GradeCalc::info() { 90 cout << "课程名称:\t" << course_name << endl; 91 cout << "排序后成绩: \t"; 92 sort(); output(); 93 cout << "最高分:\t" << max() << endl; 94 cout << "最低分:\t" << min() << endl; 95 cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl; 96 97 compute(); // 统计各分数段人数、比例 98 99 vector<string> tmp{"[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"}; 100 for(int i = tmp.size()-1; i >= 0; --i) 101 cout << tmp[i] << "\t: " << counts[i] << "人\t" 102 << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 103 }
task2.cpp
1 #include "GradeCalc.hpp" 2 #include <iomanip> 3 4 void test() { 5 int n; 6 cout << "输入班级人数: "; 7 cin >> n; 8 9 GradeCalc c1("OOP", n); 10 11 cout << "录入成绩: " << endl;; 12 c1.input(); 13 cout << "输出成绩: " << endl; 14 c1.output(); 15 16 cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl; 17 c1.info(); 18 } 19 20 int main() { 21 test(); 22 }
问题一:储存在他继承的基类vector中,通过public接口访问成绩,
问题二:计算this指向的所有元素的平均值。会,1.0可以将分子由整形转化为浮点型
问题三:缺少判断数据是否合法的过程
实验任务三:
gradecalc.hpp
View Code
task3.cpp
1 #include "GradeCalc.hpp" 2 #include <iomanip> 3 4 void test() { 5 int n; 6 cout << "输入班级人数: "; 7 cin >> n; 8 9 GradeCalc c1("OOP", n); 10 11 cout << "录入成绩: " << endl;; 12 c1.input(); 13 cout << "输出成绩: " << endl; 14 c1.output(); 15 16 cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl; 17 c1.info(); 18 } 19 20 int main() { 21 test(); 22 }
问题一:储存在类中的私有成员grade中,直接访问类中的私有成员grades
问题二:可以将基类直接作为类中的数据元素
实验任务四:
task4_1.cpp
1 #include <iostream> 2 #include <string> 3 #include <limits> 4 5 using namespace std; 6 7 void test1() { 8 string s1, s2; 9 cin >> s1 >> s2; // cin: 从输入流读取字符串, 碰到空白符(空格/回车/Tab)即结束 10 cout << "s1: " << s1 << endl; 11 cout << "s2: " << s2 << endl; 12 } 13 14 void test2() { 15 string s1, s2; 16 getline(cin, s1); // getline(): 从输入流中提取字符串,直到遇到换行符 17 getline(cin, s2); 18 cout << "s1: " << s1 << endl; 19 cout << "s2: " << s2 << endl; 20 } 21 22 void test3() { 23 string s1, s2; 24 getline(cin, s1, ' '); //从输入流中提取字符串,直到遇到指定分隔符 25 getline(cin, s2); 26 cout << "s1: " << s1 << endl; 27 cout << "s2: " << s2 << endl; 28 } 29 30 int main() { 31 cout << "测试1: 使用标准输入流对象cin输入字符串" << endl; 32 test1(); 33 cout << endl; 34 35 cin.ignore(numeric_limits<streamsize>::max(), '\n'); 36 37 cout << "测试2: 使用函数getline()输入字符串" << endl; 38 test2(); 39 cout << endl; 40 41 cout << "测试3: 使用函数getline()输入字符串, 指定字符串分隔符" << endl; 42 test3(); 43 }
task4_2.cpp
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <limits> 5 6 using namespace std; 7 8 void output(const vector<string> &v) { 9 for(auto &s: v) 10 cout << s << endl; 11 } 12 13 void test() { 14 int n; 15 while(cout << "Enter n: ", cin >> n) { 16 vector<string> v1; 17 18 for(int i = 0; i < n; ++i) { 19 string s; 20 cin >> s; 21 v1.push_back(s); 22 } 23 24 cout << "output v1: " << endl; 25 output(v1); 26 cout << endl; 27 } 28 } 29 30 int main() { 31 cout << "测试: 使用cin多组输入字符串" << endl; 32 test(); 33 }
task4_3.cpp
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <limits> 5 6 using namespace std; 7 8 void output(const vector<string> &v) { 9 for(auto &s: v) 10 cout << s << endl; 11 } 12 13 void test() { 14 int n; 15 while(cout << "Enter n: ", cin >> n) { 16 cin.ignore(numeric_limits<streamsize>::max(), '\n'); 17 18 vector<string> v2; 19 20 for(int i = 0; i < n; ++i) { 21 string s; 22 getline(cin, s); 23 v2.push_back(s); 24 } 25 cout << "output v2: " << endl; 26 output(v2); 27 cout << endl; 28 } 29 } 30 31 int main() { 32 cout << "测试: 使用函数getline()多组输入字符串" << endl; 33 test(); 34 }
问题一:确保忽略直到下一个特定分隔符(如换行符)为止的所有字符。
问题二:除输入缓冲区中可能存在的任何剩余字符,尤其是上一个输入操作后留下的换行符
实验任务五
task 5.cpp
1 #include "grm.hpp" 2 #include <iostream> 3 4 using std::cout; 5 using std::endl; 6 7 void test1() { 8 GameResourceManager<float> HP_manager(99.99); 9 cout << "当前生命值: " << HP_manager.get() << endl; 10 HP_manager.update(9.99); 11 cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl; 12 HP_manager.update(-999.99); 13 cout <<"减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl; 14 } 15 16 void test2() { 17 GameResourceManager<int> Gold_manager(100); 18 cout << "当前金币数量: " << Gold_manager.get() << endl; 19 Gold_manager.update(50); 20 cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl; 21 Gold_manager.update(-99); 22 cout <<"减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl; 23 }
grm.hpp
1 #pragma once 2 #include<iostream> 3 using namespace std; 4 template<typename T> 5 class GameResourceManager { 6 private: 7 T resouce; 8 public: 9 GameResourceManager(T Resource):resouce(Resource) {} 10 T get()const { 11 return resouce; 12 } 13 void update(T num) { 14 resouce += num; 15 if (resouce < 0) resouce = 0; 16 } 17 18 };
实验任务六
info.hpp
1 #include<iostream> 2 #include<iomanip> 3 4 using namespace std; 5 6 class Info{ 7 private: 8 string nickname; 9 string contact; 10 string city; 11 int n; 12 public: 13 Info(string nickname,string contact,string city,int n); 14 void display() const; 15 }; 16 17 Info::Info(string name,string con,string c,int n1) 18 { 19 nickname=name; 20 contact=con; 21 city=c; 22 n=n1; 23 } 24 void Info::display() const 25 { 26 cout<<setw(20)<<left<<"昵称:"<<nickname<<endl; 27 cout<<setw(20)<<left<<"联系方式:"<<contact<<endl; 28 cout<<setw(20)<<left<<"所在城市:"<<city<<endl; 29 cout<<setw(20)<<left<<"预定人数:"<<n<<endl; 30 }
task6.cpp
1 #include "Info.hpp" 2 #include <iostream> 3 #include<vector> 4 5 using namespace std; 6 7 const int capacity=100; 8 9 int main () 10 { 11 vector<Info> audience_lst; 12 cout<<"录入用户预约信息:"<<endl<<endl; 13 cout<<setw(10)<<left<<"昵称"; 14 cout<<setw(30)<<left<<"联系方式(邮箱/手机号)"; 15 cout<<setw(20)<<left<<"所在城市"; 16 cout<<setw(10)<<left<<"预定参加人数"<<endl; 17 int now_capacity=0; 18 string nickname,contact,city; 19 int n; 20 while(now_capacity<capacity && cin>>nickname>>contact>>city>>n) 21 { 22 now_capacity+=n; 23 if (now_capacity<=capacity) 24 { 25 audience_lst.push_back(Info(nickname,contact,city,n)); 26 } 27 else 28 { 29 now_capacity-=n; 30 cout<<"对不起,只剩80个位置."<<endl; 31 cout<<"1.输入u,更新(update)预定信息"<<endl; 32 cout<<"2.输入q,退出预定"<<endl; 33 cout<<"你的选择:"; 34 char choose; 35 cin>>choose; 36 if (choose=='u') 37 { 38 cout<<"请重新输入预定信息:"<<endl; 39 continue; 40 } 41 else if(choose=='q') 42 { 43 break; 44 } 45 } 46 } 47 cout<<"截至目前,一共有"<<now_capacity<<"为听众预约。预约听众信息如下:"<<endl; 48 int len=audience_lst.size(); 49 for (int i=0;i<len;i++) 50 { 51 cout<<string(50,'-')<<endl; 52 audience_lst[i].display(); 53 } 54 }
实验任务七
1 #pragma once 2 #ifndef ACCOUNT H 3 #define ACCOUNT H 4 #include"date.h" 5 #include"accumulator.h" 6 #include<string> 7 class Account { 8 private: 9 std::string id; 10 double balance; 11 static double total; 12 protected: 13 Account(const Date& date, const std::string& id); 14 void record(const Date& date, double amount, const std::string& desc); 15 void error(const std::string& msg)const; 16 public: 17 const std::string& getId()const { return id; } 18 double getBalance()const { return balance; } 19 static double getTotal() { return total; } 20 21 void show()const; 22 }; 23 class SavingsAccount :public Account { 24 private: 25 Accumulator acc; 26 double rate; 27 public: 28 SavingsAccount(const Date& date, const std::string& id, double rate); 29 double getRate()const { return rate; } 30 31 void deposit(const Date& date, double amount, const std::string& desc); 32 void withdraw(const Date& date, double amount, const std::string& desc); 33 void settle(const Date& date); 34 }; 35 class CreditAccount :public Account { 36 private: 37 Accumulator acc; 38 double credit; 39 double rate; 40 double fee; 41 double getDebt()const { 42 double balance = getBalance(); 43 return (balance < 0 ? balance : 0); 44 } 45 public: 46 CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee); 47 double getCredit()const { return credit; } 48 double getRate()const { return rate; } 49 double getAvailableCredit()const { 50 if (getBalance() < 0) 51 return credit + getBalance(); 52 else 53 return credit; 54 } 55 void deposit(const Date& date, double amount, const std::string& desc); 56 void withdraw(const Date& date, double amount, const std::string& desc); 57 void settle(const Date& date); 58 void show()const; 59 }; 60 #endif//ACCOUNT H
1 //accumulator.h 2 #pragma once 3 #ifndef ACCUMULATOR H 4 #define ACCUMULATOR H 5 #include"date.h" 6 class Accumulator { 7 private: 8 Date lastDate; 9 double value; 10 double sum; 11 public: 12 Accumulator(const Date& date, double value) :lastDate(date), value(value), sum{ 0 } { 13 } 14 15 double getSum(const Date& date)const { 16 return sum + value * date.distance(lastDate); 17 } 18 19 void change(const Date& date, double value) { 20 sum = getSum(date); 21 lastDate = date; this->value = value; 22 } 23 24 void reset(const Date& date, double value) { 25 lastDate = date; this->value = value; sum = 0; 26 } 27 }; 28 #endif//ACCUMULATOR H#pragma once
1 //date.h 2 #pragma once 3 #ifndef DATE H 4 #define DATE H 5 class Date { 6 private: 7 int year; 8 int month; 9 int day; 10 int totalDays; 11 public: 12 Date(int year, int month, int day); 13 int getYear()const { return year; } 14 int getMonth()const { return month; } 15 int getDay()const { return day; } 16 int getMaxDay()const; 17 bool isLeapYear()const { 18 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 19 } 20 void show()const; 21 int distance(const Date& date)const { 22 return totalDays - date.totalDays; 23 } 24 }; 25 #endif// DATE H
1 //account.cpp 2 #include"account.h" 3 #include<cmath> 4 #include<iostream> 5 using namespace std; 6 double Account::total = 0; 7 8 Account::Account(const Date& date, const string& id) :id{ id }, balance{ 0 } { 9 date.show(); cout << "\t#" << id << "created" << endl; 10 } 11 12 13 void Account::record(const Date& date, double amount, const string& desc) { 14 amount = floor(amount * 100 + 0.5) / 100; 15 balance += amount; 16 total += amount; 17 date.show(); 18 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 19 } 20 21 void Account::show()const { cout << id << "\tBalance:" << balance; } 22 void Account::error(const string& msg)const { 23 cout << "Error(#" << id << "):" << msg << endl; 24 } 25 26 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :Account(date, id), rate(rate), acc(date, 0) {} 27 28 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 29 record(date, amount, desc); 30 acc.change(date, getBalance()); 31 } 32 33 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 34 if (amount > getBalance()) { 35 error("not enough money"); 36 } 37 else { 38 record(date, -amount, desc); 39 acc.change(date, getBalance()); 40 } 41 } 42 43 void SavingsAccount::settle(const Date& date) { 44 double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1)); 45 if (interest != 0)record(date, interest, "interest"); 46 acc.reset(date, getBalance()); 47 } 48 49 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) :Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {} 50 51 void CreditAccount::deposit(const Date& date, double amount, const string& desc) { 52 record(date, amount, desc); 53 acc.change(date, getDebt()); 54 } 55 56 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) { 57 if (amount - getBalance() > credit) { 58 error("not enough credit"); 59 } 60 else { 61 record(date, -amount, desc); 62 acc.change(date, getDebt()); 63 } 64 } 65 66 void CreditAccount::settle(const Date& date) { 67 double interest = acc.getSum(date) * rate; 68 if (interest != 0)record(date, interest, "interest"); 69 if (date.getMonth() == 1) 70 record(date, -fee, "annual fee"); 71 acc.reset(date, getDebt()); 72 } 73 74 void CreditAccount::show()const { 75 Account::show(); 76 cout << "\tAvailable credit:" << getAvailableCredit(); 77 }
1 //date.cpp 2 #include"date.h" 3 #include<iostream> 4 #include<cstdlib> 5 using namespace std; 6 namespace { 7 const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 }; 8 } 9 Date::Date(int year, int month, int day) :year{ year }, month{ month }, day{ day } { 10 if (day <= 0 || day > getMaxDay()) { 11 cout << "Invalid date:"; 12 show(); 13 cout << endl; 14 exit(1); 15 } 16 int years = year - 1; 17 totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day; 18 if (isLeapYear() && month > 2)totalDays++; 19 } 20 int Date::getMaxDay()const { 21 if (isLeapYear() && month == 2) 22 return 29; 23 else return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1]; 24 } 25 26 void Date::show()const { 27 cout << getYear() << "-" << getMonth() << "-" << getDay(); 28 }
1 //tsak7.cpp 2 #include"account.h" 3 #include<iostream> 4 5 using namespace std; 6 7 int main() { 8 Date date(2008, 11, 1); 9 SavingsAccount sa1(date, "S3755217", 0.015); 10 SavingsAccount sa2(date, "02342342", 0.015); 11 CreditAccount ca(date, "C5392394", 10000, 0.0005, 50); 12 13 sa1.deposit(Date(2008, 11, 5), 5000, "salary"); 14 ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell"); 15 sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323"); 16 17 ca.settle(Date(2008, 12, 1)); 18 19 ca.deposit(Date(2008, 12, 1), 2016, "repay the credit"); 20 sa1.deposit(Date(2008, 12, 5), 5500, "salary"); 21 22 sa1.settle(Date(2009, 1, 1)); 23 sa2.settle(Date(2009, 1, 1)); 24 ca.settle(Date(2009, 1, 1)); 25 26 cout << endl; 27 sa1.show(); cout << endl; 28 sa2.show(); cout << endl; 29 ca.show(); cout << endl; 30 cout << "Total:" << Account::getTotal() << endl; 31 return 0; 32 }