实验四
#任务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 = 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(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(size_t 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(); }
##运行测试截图

##问题回答
问题1:
std::string course_name;:被组合的字符串对象,用于存储课程名称,标识当前成绩计算器对应的课程
std::vector<int> grades;:被组合的向量对象,核心存储容器,用于按顺序存放一门课程的所有成绩数据
std::array<int, 5> counts;:被组合的数组对象,用于存储 5 个分数段([0,60)、[60,70)、[70,80)、[80,90)、[90,100])的人数统计结果
std::array<double, 5> rates;:被组合的数组对象,用于存储上述 5 个分数段人数占总人数的比例
问题2:不合法。原因:组合关系中,GradeCalc类包含的vector<int> grades是私有成员,push_back是vector类的成员函数,并非GradeCalc类对外暴露的接口,外部代码无法直接访问私有成员的接口
double GradeCalc::median() const { if (grades.empty()) { return 0.0; } std::vector<int> temp_grades = grades; std::sort(temp_grades.begin(), temp_grades.end()); int total = temp_grades.size(); if (total % 2 == 1) { return static_cast<double>(temp_grades[total / 2]); } else { int mid_left = temp_grades[total / 2 - 1]; int mid_right = temp_grades[total / 2]; return (mid_left + mid_right) / 2.0; } }
引发错误的场景:当成多次调用input新增成绩、调用update_grade修改成绩,若未清空counts和rates,新的统计结果会与旧结果叠加,导致分数段人数和占比统计完全错误

(2)有影响;增加额外的内存操作开销
#任务2
##代码
#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(); }
##运行测试截图

##问题回答
问题1:是组合关系
class GradeCalc: private std::vector<int> {
问题2:不会自动成为GradeCalc的接口
无法编译通过。push_back是基类vector<int>的成员函数,私有继承下外部无法访问该接口
继承方式:封装性较弱,虽然私有继承限制了外部访问,但GradeCalc内部可直接使用基类的所有接口,若内部逻辑处理不当,可能直接破坏成绩数据
#任务3
##代码
#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(); }
##运行测试截图

##问题回答
class Triangle : public Graph {
class Rectangle : public Graph {
声明Star类:公有继承自Graph基类,遵循与Circle、Triangle一致的继承逻辑,并声明draw()成员函数
Graph.cpp:实现Star::draw()函数:定义星形的具体打印逻辑修改str_to_GraphType函数
添加 “字符串 star→枚举 GraphType::star” 的映射逻辑
添加 “枚举 GraphType::star→Star对象” 的创建逻辑
demo3.cpp:在test()函数中调用canvas.add("star"),将星形添加到画布
实现成本低:无需依赖 C++11 及以后的智能指针,代码逻辑直接
控制透明:开发者能清晰看到new和delete的对应关系,明确资源流向
缺点:
易引发内存泄漏:若忘记在Canvas析构中delete指针,或add()函数中未将指针存入graphs,会导致堆上的图形对象无法释放,引发内存泄漏;
易触发崩溃错误:若指针被重复delete,会引发 “双重释放” 错误
#任务4
##代码
#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; }
##运行测试截图


浙公网安备 33010602011771号