实验4
任务一:
GradeCalc.hpp
1 #pragma once 2 3 #include <vector> 4 #include <array> 5 #include <string> 6 7 class GradeCalc { 8 public: 9 GradeCalc(const std::string &cname); 10 void input(int n); // 录入n个成绩 11 void output() const; // 输出成绩 12 void sort(bool ascending = false); // 排序 (默认降序) 13 int min() const; // 返回最低分(如成绩未录入,返回-1) 14 int max() const; // 返回最高分 (如成绩未录入,返回-1) 15 double average() const; // 返回平均分 (如成绩未录入,返回0.0) 16 void info(); // 输出课程成绩信息 17 18 private: 19 void compute(); // 成绩统计 20 21 private: 22 std::string course_name; // 课程名 23 std::vector<int> grades; // 课程成绩 24 std::array<int, 5> counts; // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] 25 std::array<double, 5> rates; // 保存各分数段人数占比 26 bool is_dirty; // 脏标记,记录是否成绩信息有变更 27 };
GradeCalc.cpp
1 #include <algorithm> 2 #include <array> 3 #include <cstdlib> 4 #include <iomanip> 5 #include <iostream> 6 #include <numeric> 7 #include <string> 8 #include <vector> 9 10 #include "GradeCalc.hpp" 11 12 GradeCalc::GradeCalc(const std::string &cname):course_name{cname},is_dirty{true} { 13 counts.fill(0); 14 rates.fill(0); 15 } 16 17 void GradeCalc::input(int n) { 18 if(n < 0) { 19 std::cerr << "无效输入! 人数不能为负数\n"; 20 std::exit(1); 21 } 22 23 grades.reserve(n); 24 25 int grade; 26 27 for(int i = 0; i < n;) { 28 std::cin >> grade; 29 30 if(grade < 0 || grade > 100) { 31 std::cerr << "无效输入! 分数须在[0,100]\n"; 32 continue; 33 } 34 35 grades.push_back(grade); 36 ++i; 37 } 38 39 is_dirty = true; // 设置脏标记:成绩信息有变更 40 } 41 42 void GradeCalc::output() const { 43 for(auto grade: grades) 44 std::cout << grade << ' '; 45 std::cout << std::endl; 46 } 47 48 void GradeCalc::sort(bool ascending) { 49 if(ascending) 50 std::sort(grades.begin(), grades.end()); 51 else 52 std::sort(grades.begin(), grades.end(), std::greater<int>()); 53 } 54 55 int GradeCalc::min() const { 56 if(grades.empty()) 57 return -1; 58 59 auto it = std::min_element(grades.begin(), grades.end()); 60 return *it; 61 } 62 63 int GradeCalc::max() const { 64 if(grades.empty()) 65 return -1; 66 67 auto it = std::max_element(grades.begin(), grades.end()); 68 return *it; 69 } 70 71 double GradeCalc::average() const { 72 if(grades.empty()) 73 return 0.0; 74 75 double avg = std::accumulate(grades.begin(), grades.end(), 0.0)/grades.size(); 76 return avg; 77 } 78 79 void GradeCalc::info() { 80 if(is_dirty) 81 compute(); 82 83 std::cout << "课程名称:\t" << course_name << std::endl; 84 std::cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << std::endl; 85 std::cout << "最高分:\t" << max() << std::endl; 86 std::cout << "最低分:\t" << min() << std::endl; 87 88 const std::array<std::string, 5> grade_range{"[0, 60) ", 89 "[60, 70)", 90 "[70, 80)", 91 "[80, 90)", 92 "[90, 100]"}; 93 94 for(int i = static_cast<int>(grade_range.size())-1; i >= 0; --i) 95 std::cout << grade_range[i] << "\t: " << counts[i] << "人\t" 96 << std::fixed << std::setprecision(2) << rates[i]*100 << "%\n"; 97 } 98 99 void GradeCalc::compute() { 100 if(grades.empty()) 101 return; 102 103 counts.fill(0); 104 rates.fill(0.0); 105 106 // 统计各分数段人数 107 for(auto grade:grades) { 108 if(grade < 60) 109 ++counts[0]; // [0, 60) 110 else if (grade < 70) 111 ++counts[1]; // [60, 70) 112 else if (grade < 80) 113 ++counts[2]; // [70, 80) 114 else if (grade < 90) 115 ++counts[3]; // [80, 90) 116 else 117 ++counts[4]; // [90, 100] 118 } 119 120 // 统计各分数段比例 121 for(size_t i = 0; i < rates.size(); ++i) 122 rates[i] = counts[i] * 1.0 / grades.size(); 123 124 is_dirty = false; // 更新脏标记 125 }
task1.cpp
1 #include <iostream> 2 #include <string> 3 #include "GradeCalc.hpp" 4 5 void test() { 6 GradeCalc c1("OOP"); 7 8 std::cout << "录入成绩:\n"; 9 c1.input(5); 10 11 std::cout << "输出成绩:\n"; 12 c1.output(); 13 14 std::cout << "排序后成绩:\n"; 15 c1.sort(); c1.output(); 16 17 std::cout << "*************成绩统计信息*************\n"; 18 c1.info(); 19 20 } 21 22 int main() { 23 test(); 24 }
输出结果:

#问题1:组合关系识别
GradeCalc类声明中,逐行写出所有体现"组合"关系的成员声明,并用一句话说明每个被组合对象的功能。
std::vector<int> grades:动态数组grade,申请内存存放课程成绩
std::array<int,5> counts:申请5个int类型大小的静态数组counts,用来统计各分数段的人数
std::array<double,5> rates:申请5个double类型大小的静态数组rates,用来统计各分数段人数的比例
##问题2:接口暴露理解
如在test模块中这样使用,是否合法?如不合法,解释原因。
1 GradeCalc c("OOP"); 2 c.input(5); 3 c.push_back(97); // 合法吗?
不合法;push_back()是vector的成员函数,而c属于GradeCalc类,只能在c内部用grades.push_back()为组合的vector对象grades使用
###问题3:架构设计分析
当前设计方案中,compute在info模块中调用:
(1)连续打印3次统计信息,compute会被调用几次?标记is_dirty起什么作用?
1次;脏标记,用于判断成绩信息是否被改动,避免重复计算
(2)如新增update_grade(index,new_grade),这种设计需要更改compute调用位置吗?简洁说明理由。
不需要;compute是在最后info函数中,通过脏标记is_dirty判断是否修改成绩信息来决定掉不掉用,倘若新增update_grade(index,new_grade)更新成绩,则is_dirty==true,若要输出课程成绩信息,依旧会调用compute来重新统计成绩
####问题4:功能拓展设计
要增加"中位数"统计,不新增数据成员怎么做?在哪个函数里加?写出伪代码。
在info()中添加;
1 double median = 0; 2 std::vector<int> temp{grades}; 3 std::sort(temp.begin().temp.end()); 4 if(temp.size() % 2 == 1) 5 median = temp[(temp.size() + 1) / 2]; 6 else 7 median = (temp[temp.size() / 2] + temp[temp.size() / 2 + 1]) / 2; 8 std::cout << "中位数:\t" << std::endl;
#####问题5:数据状态管理
GradeCalc和compute中都包含代码:counts.fill(0); rates.fill(0);。
compute中能否去掉这两行?如去掉,在哪种使用场景下会引发统计错误?
不能;若去掉,则在重新统计数据时,新的数据会在旧的数据上累加
######问题6:内存管理理解
input模块中代码grades.reserve(n);如果去掉:
(1)对程序功能有影响吗?(去掉重新编译、运行,观察功能是否受影响)
没有
(2)对性能有影响吗?如有影响,用一句话陈述具体影响。
有; grades.reserve(n)可以一开始直接为grades分配n个内存空间,避免push_back()进行多次内存的重新分配和拷贝数据
任务二:
GradeCalc.hpp
1 #pragma once 2 3 #include <array> 4 #include <string> 5 #include <vector> 6 7 class GradeCalc: private std::vector<int> { 8 public: 9 GradeCalc(const std::string &cname); 10 void input(int n); // 录入n个成绩 11 void output() const; // 输出成绩 12 void sort(bool ascending = false); // 排序 (默认降序) 13 int min() const; // 返回最低分 14 int max() const; // 返回最高分 15 double average() const; // 返回平均分 16 void info(); // 输出成绩统计信息 17 18 private: 19 void compute(); // 计算成绩统计信息 20 21 private: 22 std::string course_name; // 课程名 23 std::array<int, 5> counts; // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] 24 std::array<double, 5> rates; // 保存各分数段占比 25 bool is_dirty; // 脏标记,记录是否成绩信息有变更 26 };
GradeCalc.cpp
1 #include <algorithm> 2 #include <array> 3 #include <cstdlib> 4 #include <iomanip> 5 #include <iostream> 6 #include <numeric> 7 #include <string> 8 #include <vector> 9 #include "GradeCalc.hpp" 10 11 12 GradeCalc::GradeCalc(const std::string &cname): course_name{cname}, is_dirty{true}{ 13 counts.fill(0); 14 rates.fill(0); 15 } 16 17 void GradeCalc::input(int n) { 18 if(n < 0) { 19 std::cerr << "无效输入! 人数不能为负数\n"; 20 return; 21 } 22 23 this->reserve(n); 24 25 int grade; 26 27 for(int i = 0; i < n;) { 28 std::cin >> grade; 29 if(grade < 0 || grade > 100) { 30 std::cerr << "无效输入! 分数须在[0,100]\n"; 31 continue; 32 } 33 34 this->push_back(grade); 35 ++i; 36 } 37 38 is_dirty = true; 39 } 40 41 void GradeCalc::output() const { 42 for(auto grade: *this) 43 std::cout << grade << ' '; 44 std::cout << std::endl; 45 } 46 47 void GradeCalc::sort(bool ascending) { 48 if(ascending) 49 std::sort(this->begin(), this->end()); 50 else 51 std::sort(this->begin(), this->end(), std::greater<int>()); 52 } 53 54 int GradeCalc::min() const { 55 if(this->empty()) 56 return -1; 57 58 return *std::min_element(this->begin(), this->end()); 59 } 60 61 int GradeCalc::max() const { 62 if(this->empty()) 63 return -1; 64 65 return *std::max_element(this->begin(), this->end()); 66 } 67 68 double GradeCalc::average() const { 69 if(this->empty()) 70 return 0.0; 71 72 double avg = std::accumulate(this->begin(), this->end(), 0.0) / this->size(); 73 return avg; 74 } 75 76 void GradeCalc::info() { 77 if(is_dirty) 78 compute(); 79 80 std::cout << "课程名称:\t" << course_name << std::endl; 81 std::cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << std::endl; 82 std::cout << "最高分:\t" << max() << std::endl; 83 std::cout << "最低分:\t" << min() << std::endl; 84 85 const std::array<std::string, 5> grade_range{"[0, 60) ", 86 "[60, 70)", 87 "[70, 80)", 88 "[80, 90)", 89 "[90, 100]"}; 90 91 for(int i = static_cast<int>(grade_range.size())-1; i >= 0; --i) 92 std::cout << grade_range[i] << "\t: " << counts[i] << "人\t" 93 << std::fixed << std::setprecision(2) << rates[i]*100 << "%\n"; 94 } 95 96 void GradeCalc::compute() { 97 if(this->empty()) 98 return; 99 100 counts.fill(0); 101 rates.fill(0); 102 103 // 统计各分数段人数 104 for(int grade: *this) { 105 if(grade < 60) 106 ++counts[0]; // [0, 60) 107 else if (grade < 70) 108 ++counts[1]; // [60, 70) 109 else if (grade < 80) 110 ++counts[2]; // [70, 80) 111 else if (grade < 90) 112 ++counts[3]; // [80, 90) 113 else 114 ++counts[4]; // [90, 100] 115 } 116 117 // 统计各分数段比例 118 for(size_t i = 0; i < rates.size(); ++i) 119 rates[i] = counts[i] * 1.0 / this->size(); 120 121 is_dirty = false; 122 }
task2.cpp
1 #include <iostream> 2 #include <string> 3 #include "GradeCalc.hpp" 4 5 void test() { 6 GradeCalc c1("OOP"); 7 8 std::cout << "录入成绩:\n"; 9 c1.input(5); 10 11 std::cout << "输出成绩:\n"; 12 c1.output(); 13 14 std::cout << "排序后成绩:\n"; 15 c1.sort(); c1.output(); 16 17 std::cout << "*************成绩统计信息*************\n"; 18 c1.info(); 19 20 } 21 22 int main() { 23 test(); 24 }
输出结果:

#问题1:继承关系识别 写出GradeCalc类声明体现"继承"关系的完整代码行。
class GradeCalc:private std::vector<int>
##问题2:接口暴露理解
当前继承方式下,基类vector的接口会自动成为GradeCalc的接口吗? 如在test模块中这样用,能否编译通过?用一句话解释原因。
1 GradeCalc c("OOP"); 2 c.input(5); 3 c.push_back(97); // 合法吗?
不会;不合法;push_back()时std::vector的成员函数,而std::vector在GradeCalc中是私有继承,外部无法访问
###问题3:数据访问差异
对比继承方式与组合方式内部实现数据访问的一行典型代码。说明两种方式下的封装差异带来的数据访问接口差异。
1 // 组合方式 2 for(auto grade: grades) // 通过什么接口访问数据 3 // 略 4 // 继承方式 5 for(int grade: *this) 6 // 略
组合方式:通过GradeCalc的公共接口访问数据
继承方式:GradeCalc是基类std::vector的派生类可以通过std::vector的接口访问数据
####问题4:组合 vs. 继承方案选择
你认为组合方案和继承方案,哪个更适合成绩计算这个问题场景?简洁陈述你的结论和理由。
组合;GradeCalc与std::vector更符合"has-a"的关系,成绩计算器包含成绩数据,而不是成绩计算器属于成绩数据的集合;封装程度更好
任务三:
Graph.hpp
1 #pragma once 2 3 #include <string> 4 #include <vector> 5 6 enum class GraphType {circle, triangle, rectangle}; 7 8 // Graph类定义 9 class Graph { 10 public: 11 virtual void draw() {} 12 virtual ~Graph() = default; 13 }; 14 15 // Circle类声明 16 class Circle : public Graph { 17 public: 18 void draw(); 19 }; 20 21 // Triangle类声明 22 class Triangle : public Graph { 23 public: 24 void draw(); 25 }; 26 27 // Rectangle类声明 28 class Rectangle : public Graph { 29 public: 30 void draw(); 31 }; 32 33 // Canvas类声明 34 class Canvas { 35 public: 36 void add(const std::string& type); // 根据字符串添加图形 37 void paint() const; // 使用统一接口绘制所有图形 38 ~Canvas(); // 手动释放资源 39 40 private: 41 std::vector<Graph*> graphs; 42 }; 43 44 // 4. 工具函数 45 GraphType str_to_GraphType(const std::string& s); // 字符串转枚举类型 46 Graph* make_graph(const std::string& type); // 创建图形,返回堆对象指针
Graph.cpp
1 #include <algorithm> 2 #include <cctype> 3 #include <iostream> 4 #include <string> 5 6 #include "Graph.hpp" 7 8 // Circle类实现 9 void Circle::draw() { std::cout << "draw a circle...\n"; } 10 11 // Triangle类实现 12 void Triangle::draw() { std::cout << "draw a triangle...\n"; } 13 14 // Rectangle类实现 15 void Rectangle::draw() { std::cout << "draw a rectangle...\n"; } 16 17 // Canvas类实现 18 void Canvas::add(const std::string& type) { 19 Graph* g = make_graph(type); 20 if (g) 21 graphs.push_back(g); 22 } 23 24 void Canvas::paint() const { 25 for (Graph* g : graphs) 26 g->draw(); 27 } 28 29 Canvas::~Canvas() { 30 for (Graph* g : graphs) 31 delete g; 32 } 33 34 // 工具函数实现 35 // 字符串 → 枚举转换 36 GraphType str_to_GraphType(const std::string& s) { 37 std::string t = s; 38 std::transform(s.begin(), s.end(), t.begin(), 39 [](unsigned char c) { return std::tolower(c);}); 40 41 if (t == "circle") 42 return GraphType::circle; 43 44 if (t == "triangle") 45 return GraphType::triangle; 46 47 if (t == "rectangle") 48 return GraphType::rectangle; 49 50 return GraphType::circle; // 缺省返回 51 } 52 53 // 创建图形,返回堆对象指针 54 Graph* make_graph(const std::string& type) { 55 switch (str_to_GraphType(type)) { 56 case GraphType::circle: return new Circle; 57 case GraphType::triangle: return new Triangle; 58 case GraphType::rectangle: return new Rectangle; 59 default: return nullptr; 60 } 61 }
task3.cpp
1 #include <string> 2 #include "Graph.hpp" 3 4 void test() { 5 Canvas canvas; 6 7 canvas.add("circle"); 8 canvas.add("triangle"); 9 canvas.add("rectangle"); 10 canvas.paint(); 11 } 12 13 int main() { 14 test(); 15 }
输出结果:

问题1:对象关系识别
(1)写出Graph.hpp中体现"组合"关系的成员声明代码行,并用一句话说明被组合对象的功能。
std::vector<Graph*> graphs;
存储Graph类型指针的动态数组,使它能指向派生类对象
(2)写出Graph.hpp中体现"继承"关系的类声明代码行。
class Circle:public Graph
class Triangle:public Graph
class Rectangle:public Graph
问题2:多态机制观察
(1)Graph中的draw若未声明成虚函数,Canvas::paint()中g->draw()运行结果会有何不同?
g->draw()会始终调用基类Graph中的draw()函数
(2)若Canvas类std::vector<graph*>改成std::vector,会出现什么问题?
则只能储存基类Graph,无法通过基类指针调用派生类的draw()函数
(3)若~Graph()未声明成虚函数,会带来什么问题?
只会调用基类Graph的析构函数,通过基类指针释放内存时,无法释放派生类的内存,会导致内存泄漏
问题3:扩展性思考 若要新增星形Star,需在哪些文件做哪些改动?逐一列出。
Graph.hpp
1 enum class GraphType{circle,triangle,rectangle,Star}; 2 3 class Star:public Graph { 4 public: 5 void draw(); 6 }
Graph.cpp
1 void Star::draw() { std::cout << "draw a Star...\n"; } 2 3 GraphType str_to_GraphType(const std::string& s) { 4 ...... 5 if(t == "Star") 6 return GraphType::Star; 7 } 8 Graph* make_graph(const std::string& type) { 9 switch (str_to_GraphType(type)) { 10 ...... 11 case GraphType::Star: return new Star; 12 } 13 }
问题4:资源管理 观察make_graph函数和Canvas析构函数:
(1)make_graph返回的对象在什么地方被释放?
在Canvas的析构函数中
(2)使用原始指针管理内存有何利弊?
利:简单方便
弊:需手动释放内存,容易忘记释放导致内存泄漏,不安全
任务四:
toy.hpp
1 #pragma once 2 3 #include<iostream> 4 #include<vector> 5 #include<string> 6 #include<iomanip> 7 #include<cctype> 8 9 enum class ToyType{toycar,toyplane}; 10 11 class Toy{ 12 public: 13 Toy(const std::string& cname,const std::string& ctoytype); 14 std::string get_name() const; 15 std::string get_type() const; 16 virtual void func() = 0; 17 virtual ~Toy() = default; 18 private: 19 std::string name; //玩具名称 20 std::string toytype; //玩具类型 21 }; 22 23 class ToyCar:public Toy { 24 public: 25 ToyCar(const std::string& cname,const std::string& ctoytype = "玩具汽车"); 26 void func(); 27 }; 28 29 class ToyPlane:public Toy { 30 public: 31 ToyPlane(const std::string& cname,const std::string& ctoytype = "玩具飞机"); 32 void func(); 33 }; 34 35 class ToyFactory { 36 public: 37 void info() const; 38 void add(const std::string& type,const std::string& name); 39 ~ToyFactory(); 40 private: 41 std::vector<Toy*> toys; //玩具 42 43 }; 44 45 ToyType str_to_ToyType(const std::string& type); 46 Toy* make_toy(const std::string& type,const std::string& name);
toy.cpp
1 #include"toy.hpp" 2 #include<iostream> 3 #include<vector> 4 #include<string> 5 #include<iomanip> 6 #include<cctype> 7 #include<algorithm> 8 9 ////////////// 10 Toy::Toy(const std::string& cname,const std::string& ctoytype): 11 name{cname},toytype{ctoytype}{} 12 13 std::string Toy::get_name() const { 14 return name; 15 } 16 17 std::string Toy::get_type() const { 18 return toytype; 19 } 20 //////////////////// 21 ToyCar::ToyCar(const std::string& cname,const std::string& ctoytype): 22 Toy{cname,ctoytype} {} 23 24 void ToyCar::func() { 25 std::cout << "遥控小车移动...\n"; 26 } 27 28 //////////////////// 29 ToyPlane::ToyPlane(const std::string& cname,const std::string& ctoytype): 30 Toy{cname,ctoytype} {} 31 32 void ToyPlane::func() { 33 std::cout << "遥控玩具飞机发出声响...\n"; 34 } 35 36 ////////////////// 37 void ToyFactory::add(const std::string& type,const std::string& name) { 38 Toy* p = make_toy(type,name); 39 if(p) 40 toys.push_back(p); 41 } 42 43 ToyFactory::~ToyFactory() { 44 for(Toy* i:toys) 45 delete i; 46 } 47 48 void ToyFactory::info() const { 49 std::cout << "------玩具工厂信息------" << std::endl; 50 for(Toy* i:toys) { 51 std::cout << std::left << std::setw(10) << "玩具名称:" << i->get_name() << "\n" 52 << std::setw(10) << "玩具类型:" << i->get_type() << "\n" 53 << std::setw(10) << "玩具功能:" ; 54 i->func(); 55 std::cout << "\n\n"; 56 } 57 } 58 //////////////// 59 ToyType str_to_ToyType(const std::string& type) { 60 std::string s = type; 61 std::transform(type.begin(),type.end(),s.begin(), 62 [](unsigned char c){return std::tolower(c);}); 63 if(s == "toycar") 64 return ToyType::toycar; 65 if(s == "toyplane") 66 return ToyType::toyplane; 67 return ToyType::toycar; 68 } 69 70 Toy* make_toy(const std::string& type,const std::string& name) { 71 switch(str_to_ToyType(type)) { 72 case ToyType::toycar: return new ToyCar(name); 73 case ToyType::toyplane: return new ToyPlane(name); 74 defalut: return nullptr; 75 } 76 }
task4.cpp
1 #include"toy.hpp" 2 #include<string> 3 4 void test() { 5 ToyFactory toyfactory; 6 7 toyfactory.add("toycar","玩具汽车"); 8 toyfactory.add("toyplane","玩具飞机"); 9 toyfactory.info(); 10 } 11 12 int main() { 13 test(); 14 return 0; 15 }
输出结果:

实验总结:
通过这次实验,我对继承、组合与虚函数有了更进一步的了解,我对如何合理设计类的继承层次和虚函数接口有了更深的印象,体会到了多态的实现机制
浙公网安备 33010602011771号