实验4 组合和继承

task1:

 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 };
  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);  //将array容器中值赋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);//为grade预留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 <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 }

屏幕截图 2025-11-26 081414

问题1:

std::vector<int> grades:存储课程成绩

std::array<int ,5>  counts:存储各个分数段人数

std::attay<double,5> reats:存储各分数段人数占比

问题2:

不合法,push_back()是GradeCalc类的私有成员vector<int>的函数,不可以在外部被访问

问题3:

(1)compute()函数被调用1次

    标记起到的作用是如果输入的成绩没有改动,那么不重复调用compute()进行重复计算

(2)updata_grade()函数放在compute()函数之前,使得标记is_dirty=true,调用compute()函数重新进行计算统计

问题4:

在sort()函数里面加

屏幕截图 2025-11-26 091024

问题5:

不可以,如果不为counts和rates类赋初值0,某个分数段没有学生,输出结果可能为异样的数据

问题6:

(1)对程序功能没有影响

(2)在添加元素时,可能会导致多次的释放和分配内存

 

task2:

 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 };
  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 #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:

class GradeCalc: private std::vector<int>{}
问题2:
不会自动成为类Gradecalc的接口,不能编译通过,原因是类Gradecalc对vector类的继承是私有继承
问题3:
组合类中,vector<int>grades为私有成员,通过vector类的接口访问数据
继承中,直接通过子类的this指针本身去访问
问题4:
组合,成绩计算器类主要的内容是输入输出以及计算排序等工作,类中需要一个容器类vector来存储数据,用于后续计算排序等工作,较符合has-a的关系
 
task3:
 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 }

屏幕截图 2025-11-29 142110

问题1:

(1)std::vector<Graph*> graphs 类graph的功能是所有图形类的基类,为绘制图形提供接口

(2)class Circle : public Graph,class Triangle : public Graph,class Rectangle : public Graph

问题2:

(1)结果输出的是基类draw()的函数体,即空

(2)不使用指针则无法体现多态特性,同时子类的类型与基类不同,不同子类之间的类型也不同,无法放在同一个vector<graph>中

(3)导致仅释放基类的内存,导致内存释放不完全

问题3:

hpp文件中第6行:在enum class GraphType中加入Star类型

hpp文件Rectangle类声明后面加上Star类的声明

cpp文件Rectangle类实现后面加上Star类的实现

cpp文件字符串->枚举类型转换中加上if(t=="star")return GraphType::star

cpp文件创建图形中加上case GraphType::star:return new Star

问题4:

(1)在Canves类的析构函数中被释放

(2)利:内存分配灵活,操作更直接

 弊:存在野指针的问题,内存容易泄露

task4:

 1、问题场景描述:设计了三款玩具,分别为三种动物:狐狸、兔子、小狗,类型有两种分别为录音娃娃和捏捏叫,录音娃娃可以播放一句音频,捏捏叫捏一下就可以发出对应动物的叫声

2、Toy和Rabbit,Fox,Puppy之间是继承关系,因为它们三个都是Toy的实例,是is-a的关系;Toy Factory和Toy之间是组合关系,它们是has-a的关系

 1 #pragma once
 2 
 3 #include<iostream>
 4 #include<vector>
 5 #include<string>
 6 enum class ToyType{Rabbit,Fox,Puppy};
 7  
 8 //毛绒玩具类 
 9 class Toy{
10 public:
11     Toy(std::string name_,std::string type_);
12     
13     virtual void func(){}
14     
15 public:
16     std::string name;
17     std::string type;    
18     
19 };
20 //兔子 
21 class Rabbit:public Toy{
22 public:
23     Rabbit(std::string name_,std::string type_);
24     
25     void func();
26 };
27 //狐狸 
28 class Fox:public Toy{
29 public:
30     Fox(std::string name_,std::string type_);
31     
32     void func();
33 };
34 
35 //狗狗 
36 class Puppy:public Toy{
37 public:
38     Puppy(std::string name_,std::string type_);
39     
40     void func();
41 }; 
42 
43 //玩具工厂类 
44 class ToyFactory{
45 public:
46     void add(const std::string& type1,const std::string& name,const std::string& type);
47     void display()const;
48     
49 private:
50     std::vector<Toy*>toys;
51 };
52 
53 ToyType str_to_ToyType(const std::string& s);  
54 Toy* make_Toy(const std::string& type1,const std::string& name,const std::string& type);  
 1 #include"toy.hpp"
 2 #include<iostream>
 3 #include<vector>
 4 #include<cctype>
 5 #include<string>
 6 #include<algorithm>
 7 
 8 Toy::Toy(std::string name_,std::string type_):name{name_},type{type_}{}
 9 
10 Rabbit::Rabbit(std::string name_,std::string type_):Toy(name_,type_){}
11     
12 void Rabbit::func(){
13         std::cout<<"播放录音:You can be right,or you can be happy!"<<std::endl; 
14     } 
15 
16 Fox::Fox(std::string name_,std::string type_):Toy(name_,type_){}
17     
18 void Fox::func(){
19         std::cout<<"播放录音:No one tells me what I can or can't be!"<<std::endl;
20     }
21 
22 
23 Puppy::Puppy(std::string name_,std::string type_):Toy(name_,type_){}
24     
25 void Puppy::func(){
26         std::cout<<"捏一下:汪汪"<<std::endl;
27     }
28 
29 
30 void ToyFactory::add(const std::string& type1,const std::string& name,const std::string& type){
31     Toy* t=make_Toy(type1,name,type);
32     toys.push_back(t);
33 }
34 
35 void ToyFactory::display()const{
36     for(Toy* i:toys){
37         std::cout<<"名称:"<<i->name<<std::endl;
38         std::cout<<"类型:"<<i->type<<std::endl;
39         std::cout<<"特异功能:";
40         i->func(); 
41     }
42 }
43 
44 ToyType str_to_ToyType(const std::string& s) {
45     std::string t = s;
46     std::transform(s.begin(), s.end(), t.begin(),
47                    [](unsigned char c) { return std::tolower(c);});
48 
49     if (t == "rabbit")   
50         return ToyType::Rabbit;
51 
52     if (t == "fox") 
53         return ToyType::Fox;
54 
55     if (t == "puppy")
56         return ToyType::Puppy;
57 
58     return ToyType::Rabbit;   // 缺省返回
59 }
60 
61 Toy* make_Toy(const std::string& type1,const std::string& name,const std::string& type) {
62     switch (str_to_ToyType(type1)) {
63     case ToyType::Rabbit:     return new Rabbit(name,type);
64     case ToyType::Fox:   return new Fox(name,type);
65     case ToyType::Puppy:  return new Puppy(name,type);
66     default: return nullptr;
67     }
68 }
 1 #include"toy.hpp"
 2 #include<iostream>
 3 #include<string>
 4 
 5 
 6 void test(){
 7     ToyFactory toyfactory;
 8     
 9     toyfactory.add("Rabbit","judy","录音娃娃");
10     toyfactory.add("Fox","nick","录音娃娃");
11     toyfactory.add("Puppy","小白","捏捏叫");
12     toyfactory.display();
13 }
14 int main(){
15     test();
16 }

屏幕截图 2025-12-01 161334

 

posted @ 2025-12-01 16:20  sunishope  阅读(2)  评论(0)    收藏  举报