实验四 组合与继承
实验1
1.源代码
#pragma once #include <vector> #include <array> #include <string> class GradeCalc { public: GradeCalc(const std::string &cname); void input(int n); // 录入n个成绩 void output() const; // 输出成绩 void sort(bool ascending = false); // 排序 (默认降序) int min() const; // 返回最低分(如成绩未录入,返回-1) int max() const; // 返回最高分 (如成绩未录入,返回-1) double average() const; // 返回平均分 (如成绩未录入,返回0.0) void info(); // 输出课程成绩信息 private: void compute(); // 成绩统计 private: std::string course_name; // 课程名 std::vector<int> grades; // 课程成绩 std::array<int, 5> counts; // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] std::array<double, 5> rates; // 保存各分数段人数占比 bool is_dirty; // 脏标记,记录是否成绩信息有变更 };
#include <algorithm> #include <array> #include <cstdlib> #include <iomanip> #include <iostream> #include <numeric> #include <string> #include <vector> #include "GradeCalc.hpp" GradeCalc::GradeCalc(const std::string &cname):course_name{cname},is_dirty{true} { counts.fill(0); rates.fill(0); } void GradeCalc::input(int n) { if(n < 0) { std::cerr << "无效输入! 人数不能为负数\n"; std::exit(1); } grades.reserve(n); int grade; for(int i = 0; i < n;) { std::cin >> grade; if(grade < 0 || grade > 100) { std::cerr << "无效输入! 分数须在[0,100]\n"; continue; } grades.push_back(grade); ++i; } is_dirty = true; // 设置脏标记:成绩信息有变更 } void GradeCalc::output() const { for(auto grade: grades) std::cout << grade << ' '; std::cout << std::endl; } void GradeCalc::sort(bool ascending) { if(ascending) std::sort(grades.begin(), grades.end()); else std::sort(grades.begin(), grades.end(), std::greater<int>()); } int GradeCalc::min() const { if(grades.empty()) return -1; auto it = std::min_element(grades.begin(), grades.end()); return *it; } int GradeCalc::max() const { if(grades.empty()) return -1; auto it = std::max_element(grades.begin(), grades.end()); return *it; } double GradeCalc::average() const { if(grades.empty()) return 0.0; double avg = std::accumulate(grades.begin(), grades.end(), 0.0)/grades.size(); return avg; } void GradeCalc::info() { if(is_dirty) compute(); std::cout << "课程名称:\t" << course_name << std::endl; std::cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << std::endl; std::cout << "最高分:\t" << max() << std::endl; std::cout << "最低分:\t" << min() << std::endl; const std::array<std::string, 5> grade_range{"[0, 60) ", "[60, 70)", "[70, 80)", "[80, 90)", "[90, 100]"}; for(int i = grade_range.size()-1; i >= 0; --i) std::cout << grade_range[i] << "\t: " << counts[i] << "人\t" << std::fixed << std::setprecision(2) << rates[i]*100 << "%\n"; } void GradeCalc::compute() { if(grades.empty()) return; counts.fill(0); rates.fill(0.0); // 统计各分数段人数 for(auto grade:grades) { if(grade < 60) ++counts[0]; // [0, 60) else if (grade < 70) ++counts[1]; // [60, 70) else if (grade < 80) ++counts[2]; // [70, 80) else if (grade < 90) ++counts[3]; // [80, 90) else ++counts[4]; // [90, 100] } // 统计各分数段比例 for(int i = 0; i < rates.size(); ++i) rates[i] = counts[i] * 1.0 / grades.size(); is_dirty = false; // 更新脏标记 }
#include <iostream> #include <string> #include "GradeCalc.hpp" void test() { GradeCalc c1("OOP"); std::cout << "录入成绩:\n"; c1.input(5); std::cout << "输出成绩:\n"; c1.output(); std::cout << "排序后成绩:\n"; c1.sort(); c1.output(); std::cout << "*************成绩统计信息*************\n"; c1.info(); } int main() { test(); }
2. 运行截图

3.问题回答
问题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时重新分配内存,复制数据,导致性能下降。
实验2
1.源代码
#pragma once #include <array> #include <string> #include <vector> class GradeCalc: private std::vector<int> { public: GradeCalc(const std::string &cname); void input(int n); // 录入n个成绩 void output() const; // 输出成绩 void sort(bool ascending = false); // 排序 (默认降序) int min() const; // 返回最低分 int max() const; // 返回最高分 double average() const; // 返回平均分 void info(); // 输出成绩统计信息 private: void compute(); // 计算成绩统计信息 private: std::string course_name; // 课程名 std::array<int, 5> counts; // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] std::array<double, 5> rates; // 保存各分数段占比 bool is_dirty; // 脏标记,记录是否成绩信息有变更 };
#include <algorithm> #include <array> #include <cstdlib> #include <iomanip> #include <iostream> #include <numeric> #include <string> #include <vector> #include "GradeCalc.hpp" GradeCalc::GradeCalc(const std::string &cname): course_name{cname}, is_dirty{true}{ counts.fill(0); rates.fill(0); } void GradeCalc::input(int n) { if(n < 0) { std::cerr << "无效输入! 人数不能为负数\n"; return; } this->reserve(n); int grade; for(int i = 0; i < n;) { std::cin >> grade; if(grade < 0 || grade > 100) { std::cerr << "无效输入! 分数须在[0,100]\n"; continue; } this->push_back(grade); ++i; } is_dirty = true; } void GradeCalc::output() const { for(auto grade: *this) std::cout << grade << ' '; std::cout << std::endl; } void GradeCalc::sort(bool ascending) { if(ascending) std::sort(this->begin(), this->end()); else std::sort(this->begin(), this->end(), std::greater<int>()); } int GradeCalc::min() const { if(this->empty()) return -1; return *std::min_element(this->begin(), this->end()); } int GradeCalc::max() const { if(this->empty()) return -1; return *std::max_element(this->begin(), this->end()); } double GradeCalc::average() const { if(this->empty()) return 0.0; double avg = std::accumulate(this->begin(), this->end(), 0.0) / this->size(); return avg; } void GradeCalc::info() { if(is_dirty) compute(); std::cout << "课程名称:\t" << course_name << std::endl; std::cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << std::endl; std::cout << "最高分:\t" << max() << std::endl; std::cout << "最低分:\t" << min() << std::endl; const std::array<std::string, 5> grade_range{"[0, 60) ", "[60, 70)", "[70, 80)", "[80, 90)", "[90, 100]"}; for(int i = static_cast<int>(grade_range.size())-1; i >= 0; --i) std::cout << grade_range[i] << "\t: " << counts[i] << "人\t" << std::fixed << std::setprecision(2) << rates[i]*100 << "%\n"; } void GradeCalc::compute() { if(this->empty()) return; counts.fill(0); rates.fill(0); // 统计各分数段人数 for(int grade: *this) { if(grade < 60) ++counts[0]; // [0, 60) else if (grade < 70) ++counts[1]; // [60, 70) else if (grade < 80) ++counts[2]; // [70, 80) else if (grade < 90) ++counts[3]; // [80, 90) else ++counts[4]; // [90, 100] } // 统计各分数段比例 for(size_t i = 0; i < rates.size(); ++i) rates[i] = counts[i] * 1.0 / this->size(); is_dirty = false; }
#include <iostream> #include <string> #include "GradeCalc.hpp" void test() { GradeCalc c1("OOP"); std::cout << "录入成绩:\n"; c1.input(5); std::cout << "输出成绩:\n"; c1.output(); std::cout << "排序后成绩:\n"; c1.sort(); c1.output(); std::cout << "*************成绩统计信息*************\n"; c1.info(); } int main() { test(); }
2.运行截图

3.问题回答
问题1:是组合关系
class GradeCalc: private std::vector<int> {
问题2:不会自动成为GradeCalc的接口
无法编译通过。push_back是基类vector<int>的成员函数,私有继承下外部无法访问该接口
继承方式:封装性较弱,虽然私有继承限制了外部访问,但GradeCalc内部可直接使用基类的所有接口,若内部逻辑处理不当,可能直接破坏成绩数据
#pragma once #include <string> #include <vector> enum class GraphType {circle, triangle, rectangle}; // Graph类定义 class Graph { public: virtual void draw() {} virtual ~Graph() = default; }; // Circle类声明 class Circle : public Graph { public: void draw(); }; // Triangle类声明 class Triangle : public Graph { public: void draw(); }; // Rectangle类声明 class Rectangle : public Graph { public: void draw(); }; // Canvas类声明 class Canvas { public: void add(const std::string& type); // 根据字符串添加图形 void paint() const; // 使用统一接口绘制所有图形 ~Canvas(); // 手动释放资源 private: std::vector<Graph*> graphs; }; // 4. 工具函数 GraphType str_to_GraphType(const std::string& s); // 字符串转枚举类型 Graph* make_graph(const std::string& type); // 创建图形,返回堆对象指针
#include <algorithm> #include <cctype> #include <iostream> #include <string> #include "Graph.hpp" // Circle类实现 void Circle::draw() { std::cout << "draw a circle...\n"; } // Triangle类实现 void Triangle::draw() { std::cout << "draw a triangle...\n"; } // Rectangle类实现 void Rectangle::draw() { std::cout << "draw a rectangle...\n"; } // Canvas类实现 void Canvas::add(const std::string& type) { Graph* g = make_graph(type); if (g) graphs.push_back(g); } void Canvas::paint() const { for (Graph* g : graphs) g->draw(); } Canvas::~Canvas() { for (Graph* g : graphs) delete g; } // 工具函数实现 // 字符串 → 枚举转换 GraphType str_to_GraphType(const std::string& s) { std::string t = s; std::transform(s.begin(), s.end(), t.begin(), [](unsigned char c) { return std::tolower(c);}); if (t == "circle") return GraphType::circle; if (t == "triangle") return GraphType::triangle; if (t == "rectangle") return GraphType::rectangle; return GraphType::circle; // 缺省返回 } // 创建图形,返回堆对象指针 Graph* make_graph(const std::string& type) { switch (str_to_GraphType(type)) { case GraphType::circle: return new Circle; case GraphType::triangle: return new Triangle; case GraphType::rectangle: return new Rectangle; default: return nullptr; } }
#include <string> #include "Graph.hpp" void test() { Canvas canvas; canvas.add("circle"); canvas.add("triangle"); canvas.add("rectangle"); canvas.paint(); } int main() { test(); }
2.运行截图

3.问题回答
问题一:
答:(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) 利:实现简单,直接控制对象生命周期;
弊:易出现内存泄漏、悬空指针等问题,需手动管理内存。
#pragma once #include <string> #include <vector> using namespace std; class Toy { public: Toy(const string& name, const string& type); virtual ~Toy() = default; void showInfo() const; virtual void specialFunction() = 0; protected: string toyName; string toyType; string brand = "萌趣工坊"; float price = 99.9f; }; class DialogToy : public Toy { public: DialogToy(const string& name, const string& type); void specialFunction() override; private: string dialogContent = "你好"; }; class MusicToy : public Toy { public: MusicToy(const string& name, const string& type); void specialFunction() override; private: string musicName = "晴天"; }; class LightToy : public Toy { public: LightToy(const string& name, const string& type); void specialFunction() override; private: string lightColor = "蓝色"; }; class ToyFactory { public: ~ToyFactory(); void addToy(Toy* toy); void showAllToys() const; private: std::vector<Toy*> toys; };
#include "Toy.hpp" #include <iostream> using namespace std; Toy::Toy(const string& name, const string& type) : toyName(name), toyType(type) {} void Toy::showInfo() const { cout << "玩具名称:" << toyName << endl; cout << "玩具类型:" << toyType <<endl; cout << "品牌:" << brand << endl; cout << "价格:" << price << "元" << endl; } DialogToy::DialogToy(const string& name, const string& type) : Toy(name, type) {} void DialogToy::specialFunction() { cout << "【功能】智能对话:" << dialogContent << endl; } MusicToy::MusicToy(const string& name, const string& type) : Toy(name, type) {} void MusicToy::specialFunction() { cout << "【功能】播放音乐:" << musicName << endl; } LightToy::LightToy(const string& name, const string& type) : Toy(name, type) {} void LightToy::specialFunction() { cout << "【功能】发光:发出" << lightColor << "的光" << endl; } ToyFactory::~ToyFactory() { for (Toy* toy : toys) { delete toy; } toys.clear(); } void ToyFactory::addToy(Toy* toy) { if (toy != nullptr) { toys.push_back(toy); } } void ToyFactory::showAllToys() const { cout << "===== 玩具工厂所有玩具信息 =====" <<endl; for (size_t i = 0; i < toys.size(); ++i) { cout << "\n第" << i + 1 << "个玩具:" << endl; toys[i]->showInfo(); toys[i]->specialFunction(); cout << "-------------------------" << endl; } }
#include "Toy.hpp" int main() { ToyFactory factory; factory.addToy(new DialogToy("智能小狗", "对话类玩具")); factory.addToy(new MusicToy("音乐兔子", "音乐类玩具")); factory.addToy(new LightToy("发光猫咪", "发光类玩具")); factory.showAllToys(); return 0; }
2.运行截图

实验总结
本次实验主要对组合和继承方法进行运用,通过这次实验,我对继承、组合与虚函数有了更进一步的了解,我对如何合理设计类的继承层次和虚函数接口有了更深的印象,体会到了多态的实现机制。

浙公网安备 33010602011771号