实验四
任务一:
源代码:
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 #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 }
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 }

问题1:组合关系识别
GradeCalc类声明中,逐行写出所有体现"组合"关系的成员声明,并用一句话说明每个被组合对象的功能。
答:std::vector<int> grades; 保存课程成绩
std::array<int, 5> counts; 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
std::array<double, 5> rates; 保存各分数段人数占比
问题2:接口暴露理解
如在test模块中这样使用,是否合法?如不合法,解释原因。
GradeCalc c("OOP");
c.inupt(5);
c.push_back(97);
答:不合法。grades是GradeCalc的私有成员,外部函数无法直接访问。
问题3:架构设计分析
当前设计方案中,compute在info模块中调用:
(1)连续打印3次统计信息,compute会被调用几次?标记is_dirty起到什么作用?
答:一次。标记更新信息,防止再次统计改变信息。
(2)如新增update_grade(index, new_grade),这种设计需要更改compute调用位置吗?简洁说明理由。
答:需要。需要把compute的调用位置放在updata_grade之后,这样才能把我们更新后的成员信息进行compute操作,即再次更新各分数段的成绩及其比例。
问题4:功能扩展设计
要增加"中位数"统计,不新增数据成员怎么做?在哪个函数里加?写出伪代码。
答:
1. 在 GradeCalc.h 的 public 区域添加声明:
double median() const;
2. 在 GradeCalc.cpp 中实现:
double GradeCalc::median() const {
if (grades.empty()) return 0.0;
std::vector<int> temp = grades;
std::sort(temp.begin(), temp.end());
size_t n = temp.size();
return (n % 2 == 1) ? temp[n/2] : (temp[n/2-1] + temp[n/2])/2.0;
}
3. 在 info() 函数中添加输出:
std::cout << "中位数: " << median() << std::endl;
问题5:数据状态管理
GradeCalc和compute中都包含代码:counts.fill(0); rates.fill(0);。
compute中能否去掉这两行?如去掉,在哪种使用场景下会引发统计错误?
答:不能。如果去掉,就无法每次初始化,调用compute函数时,会造成旧数据重复统计。
问题6:内存管理理解
input模块中代码grades.reserve(n);如果去掉:
(1)对程序功能有影响吗?(去掉重新编译、运行,观察功能是否受影响)
答:无影响。
(2)对性能有影响吗?如有影响,用一句话陈述具体影响。
答:有影响。去掉后,vector会在push_back时重新分配内存,复制数据,导致性能下降。
任务二:
源代码:
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 #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 }
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 };
运行结果截图:

问题一:
答:class GradeCalc: private std::vector<int>
问题二:
答:不会。GradeCalc是私有继承vector<int>,外部函数无法直接调用。
问题三:
答:组合;通过类内定义的成员变量访问数据,封装性强;
继承:通过派生类自身访问数据,封装性弱。
问题四:
答:我觉得组合方式更好,统计成绩能更好的对数据进行封装操作。
任务三:
源代码:
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); // 创建图形,返回堆对象指针
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 }
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)std::vector<Graph*> graphs; Canvas类组合了多个Graph对象指针,实现了对图形的集中管理。
(2)class Circle : public Graph{}
class Circle : public Graph{}
class Rectangle : public Graph {}
问题二:
答:(1)若不是虚函数,会固定调用Graph::draw(),无实际输出。
(2)会丢失子类独有的信息,无法触发多态。
(3)会导致删除Graph*指针时,只会调用Graph的析构函数,不会调用子类析构函数。导致内存泄漏。
问题三:
答:
1. 在 GraphType 枚举中添加 star ;
2. 定义 class Star : public Graph 并实现 draw() ;
3. 在 str_to_GraphType 函数中增加 "star" 到 GraphType::star 的映射;4. 在 make_graph 函数的 switch 中增加 case GraphType::star: return new Star; 。
问题四:
答:(1) 在 Canvas 的析构函数中,通过 delete g 释放 graphs 中的 Graph* 指针。
(2) 利:实现简单,直接控制对象生命周期;
弊:易出现内存泄漏、悬空指针等问题,需手动管理内存。
任务四:
源代码:
1 #include <iostream> 2 #include "Toy.hpp" 3 4 void testToyFactory() { 5 ToyFactory factory; 6 7 // 向工厂添加不同玩具 8 factory.addToy(new SingingPig("会唱歌的小猪")); 9 factory.addToy(new GlowingRabbit("会发光的小兔")); 10 factory.addToy(new TalkingCat("能对话的小猫")); 11 12 // 显示所有玩具信息 13 factory.showAllToys(); 14 }a 15 16 int main() { 17 testToyFactory(); 18 return 0; 19 }
1 #include "Toy.hpp" 2 #include <iostream> 3 4 // Toy类实现 5 Toy::Toy(const std::string& n, const std::string& t) 6 : name(n), type(t) {} 7 8 std::string Toy::getName() const { 9 return name; 10 } 11 12 std::string Toy::getType() const { 13 return type; 14 } 15 16 17 // SingingPig类实现 18 SingingBear::SingingBear(const std::string& n) 19 : Toy(n, "电动毛绒玩具") {} 20 21 void SingingPig::specialFunction() const { 22 std::cout << "【" << name << "】功能:可以播放儿童歌曲" << std::endl; 23 } 24 25 26 // GlowingRabbit类实现 27 GlowingRabbit::GlowingRabbit(const std::string& n) 28 : Toy(n, "声光毛绒玩具") {} 29 30 void GlowingRabbit::specialFunction() const { 31 std::cout << "【" << name << "】功能:耳朵会布林布林发光" << std::endl; 32 }a 33 34 35 // TalkingCat类实现 36 TalkingCat::TalkingCat(const std::string& n) 37 : Toy(n, "智能毛绒玩具") {} 38 39 void TalkingCat::specialFunction() const { 40 std::cout << "【" << name << "】功能:能够和小盆友对话" << std::endl; 41 } 42 43 44 // ToyFactory类实现 45 ToyFactory::~ToyFactory() { 46 // 释放玩具内存 47 for (Toy* t : toys) { 48 delete t; 49 } 50 } 51 52 void ToyFactory::addToy(Toy* t) { 53 if (t != nullptr) { 54 toys.push_back(t); 55 } 56 } 57 58 void ToyFactory::showAllToys() const { 59 std::cout << "\n===== 玩具工厂产品列表 =====" << std::endl; 60 for (const Toy* t : toys) { 61 std::cout << "名称:" << t->getName() 62 << " | 类型:" << t->getType() << " | "; 63 t->specialFunction(); // 多态调用特异功能 64 } 65 }
1 #pragma once 2 #include <string> 3 #include <vector> 4 5 // 毛绒玩具基类(抽象类) 6 class Toy { 7 protected: 8 std::string name; // 玩具名称 9 std::string type; // 玩具类型 10 public: 11 Toy(const std::string& n, const std::string& t); 12 virtual ~Toy() = default; 13 14 // 纯虚函数:特异功能(多态接口) 15 virtual void specialFunction() const = 0; 16 17 // 获取玩具信息 18 std::string getName() const; 19 std::string getType() const; 20 }; 21 22 23 // 具体玩具1:会唱歌的毛绒猪 24 class SingingPig : public Toy { 25 public: 26 SingingBear(const std::string& n); 27 void specialFunction() const override; 28 }; 29 30 31 // 具体玩具2:会发光的毛绒兔 32 class GlowingRabbit : public Toy { 33 public: 34 GlowingRabbit(const std::string& n); 35 void specialFunction() const override; 36 }; 37 38 39 // 具体玩具3:会说话的毛绒猫 40 class TalkingCat : public Toy { 41 public: 42 TalkingCat(const std::string& n); 43 void specialFunction() const override; 44 }; 45 46 47 // 玩具工厂类(组合多个Toy对象) 48 class ToyFactory { 49 private: 50 std::vector<Toy*> toys; // 组合:工厂包含多个玩具 51 public: 52 ~ToyFactory(); 53 54 // 添加玩具到工厂 55 void addToy(Toy* t); 56 57 // 显示所有玩具信息 58 void showAllToys() const; 59 };
运行结果截图:

1. 继承关系:
SingingPig、 GlowingRabbit 、 TalkingCat 均公有继承自抽象基类 Toy ,通过重写纯虚函数 specialFunction() 实现多态。
2. 组合关系:
ToyFactory 类组合了 std::vector<Toy*> 成员,用于管理多个玩具对象,体现“工厂包含多个玩具”。
五、实验总结:
本次实验主要对组合和继承方法进行运用。

浙公网安备 33010602011771号