实验4

实验任务1:

代码:

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);
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::vector<int> grades;
24     std::array<int, 5> counts;
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     for(auto grade:grades) {
107         if(grade < 60)
108             ++counts[0];
109         else if (grade < 70)
110             ++counts[1];
111         else if (grade < 80)
112             ++counts[2];
113         else if (grade < 90)
114             ++counts[3];
115         else
116             ++counts[4];
117     }
118 
119     for(size_t i = 0; i < rates.size(); ++i)
120         rates[i] = counts[i] * 1.0 / grades.size();
121     
122     is_dirty = false;
123 }

 

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 }

 

运行测试截图:

image

 

回答问题:

问题1:std::vector<int> grades;:存储课程的所有成绩数据;std::array<int, 5> counts;:存储各分数段([0,60) 等)的人数统计结果;std::array<double, 5> rates;:存储各分数段人数的占比统计结果。

问题2:不合法。push_back是vector<int>的接口,GradeCalc并未公开该接口。

问题3:

(1)compute只会被调用一次。is_dirty标记避免重复计算。

(2)需要,应在 update_grade中设置is_dirty=true,确保统计信息在下次 info 时更新

问题4:在info函数中添加。

std::vector<int> temp = grades;
std::sort(temp.begin(), temp.end());
double median;
if (temp.size() % 2 == 1) {
  median = temp[temp.size() / 2];
}

else {
 median = (temp[temp.size()/2 - 1] + temp[temp.size()/2]) / 2.0;
}
std::cout << "中位数:\t" << std::fixed << std::setprecision(2) << median << std::endl;

问题5:不能去掉。如果去掉,连续多次调用 info 会导致 counts 和 rates 累加错误。

问题6:

(1)无影响

(2)有影响,去掉 reserve 会导致多次 push_back 时频繁扩容,降低性能。

 

实验任务2:

代码:

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 }

 

运行测试截图:

image

 

回答问题:

问题1:class GradeCalc: private std::vector<int>

问题2:不会。因为是私有继承,基类接口对外不可见。代码 c.push_back(97) 不合法,编译错误。

问题3:组合:for(auto grade: grades):通过成员变量访问;继承:for(int grade: *this): 通过基类自身访问。继承方式更直接但封装性较弱。

问题4:组合更适合。成绩计算器是 “使用容器存储成绩”,而非 “本身是容器”,组合更符合逻辑,封装更好,易于维护。

 

实验任务3:

代码:

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 }

 

运行测试截图:

image

 

回答问题:

问题1:

(1)组合:std::vector<Graph*> graphs;      存储图形对象指针

(2)继承:

class Circle : public Graph {

class Triangle : public Graph {

class Rectangle : public Graph {

问题2:

(1)g->draw() 会调用基类 Graph::draw,不执行子类重写。

(2)会引发对象切片,丢失子类信息。

(3)可能导致子类资源泄漏。

问题3:

1.Graph.hpp:在GraphType枚举中添加star;声明class Star : public Graph { public: void draw(); };。
2.Graph.cpp:实现Star::draw( );在str_to_GraphType中添加if (t == "star") return GraphType::star; ;在make_graph的switch中添加case GraphType::star: return new Star;

问题4:

(1)在 Canvas 的析构函数中释放。

(2)利:直接控制内存;弊:易发生泄漏或重复释放。

实验任务4:

Toy.hpp

 1 #define TOY_H
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 class Toy {
 7 protected:
 8     string toyName;
 9     string toyType;
10     int toyPrice;
11 public:
12     Toy(string name, string type, int price) 
13         : toyName(name), toyType(type), toyPrice(price) {}
14 
15     virtual void specialSkill() const;
16 
17     string getName() const { return toyName; }
18     string getType() const { return toyType; }
19     int getPrice() const { return toyPrice; }
20 };
21 
22 class TalkToy : public Toy {
23 public:
24     TalkToy(string name, int price) 
25         : Toy(name, "毛绒-对话型", price) {}
26 
27     void specialSkill() const override;
28 };
29 
30 class SwingToy : public Toy {
31 public:
32     SwingToy(string name, int price) 
33         : Toy(name, "毛绒-摇摆型", price) {}
34 
35     void specialSkill() const override;
36 };
37 
38 class ToyFactory {
39 private:
40     vector<Toy*> toyList;
41 public:
42     ~ToyFactory();
43 
44     void addToy(Toy* toy);
45 
46     void showAllToys() const;
47 };

 

Toy.cpp

 1 #include "Toy.hpp"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 void Toy::specialSkill() const {
 6     cout << "该玩具暂无特异功能" << endl;
 7 }
 8 
 9 void TalkToy::specialSkill() const {
10     cout << "" << toyName << "】:你好呀!我是你的毛绒伙伴~" << endl;
11 }
12 
13 void SwingToy::specialSkill() const {
14     cout << "" << toyName << "】:左右摇摆,快乐跳舞~" << endl;
15 }
16 
17 ToyFactory::~ToyFactory() {
18     for (int i = 0; i < toyList.size(); i++) {
19         delete toyList[i];
20     }
21     toyList.clear();
22 }
23 
24 void ToyFactory::addToy(Toy* toy) {
25     toyList.push_back(toy);
26 }
27 
28 void ToyFactory::showAllToys() const {
29     cout << "\n===== 玩具工厂库存 =====\n";
30     for (int i = 0; i < toyList.size(); i++) {
31         cout << "名称:" << toyList[i]->getName() 
32              << " | 类型:" << toyList[i]->getType() 
33              << " | 价格:" << toyList[i]->getPrice() << "" 
34              << " | 功能:";
35         toyList[i]->specialSkill();
36     }
37 }

 

task4.cpp

 1 #include "Toy.hpp"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int main() {
 6     ToyFactory myFactory;
 7 
 8     myFactory.addToy(new TalkToy("泰迪熊", 89));
 9     myFactory.addToy(new SwingToy("兔子玩偶", 69));
10     myFactory.addToy(new TalkToy("机器猫", 129));
11 
12     myFactory.showAllToys();
13 
14     return 0;
15 }

 

image

 场景描述:针对电子毛绒玩具生产企业的玩具管理需求:企业生产多种功能的电子毛绒玩具(如对话型、发光型等),需统一管理所有玩具的基础信息(名称、类型、价格等),并通过同一个接口调用不同玩具的特异功能,避免重复开发,同时支持灵活扩展新玩具类型。

 

posted @ 2025-12-02 23:51  雅ya  阅读(1)  评论(0)    收藏  举报