实验4
task1:
#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; // 更新脏标记 }
#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 <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:
course_name:存储课程名称。
grades:存储所有学生成绩。
counts:存储5个分数段的人数。
rates:存储5个分数段人数的比例。
问题2:不合法。
因为 push_back 是 std::vector 的成员函数,而 grades 是私有成员,外部无法直接调用 c.grades.push_back,也没有在 GradeCalc 类中公开 push_back 接口。
问题3:
(1)1次。作用是判断成绩是否已更新。
(2)不需要更改 compute() 的调用位置,因为 compute() 只在 info() 中被调用,且受 is_dirty 控制。
问题4:可以在 info() 中增加中位数统计,不需要新增数据成员。
void GradeCalc::info() { if(is_dirty) compute(); if(!grades.empty()) { std::vector<int> sorted = grades; std::sort(sorted.begin(), sorted.end()); double median; if(sorted.size() % 2 == 0) median = (sorted[sorted.size()/2-1] + sorted[sorted.size()/2]) / 2.0; else median = sorted[sorted.size()/2]; std::cout << "中位数:\t" << median << std::endl; } }
问题5:不能去掉,如去掉,多次调用 compute() 时,会在原有的 counts 和 rates 基础上累加,导致统计结果错误。
问题6:
(1)对功能没有影响。
(2)对性能有影响。每次 push_back 时若容量不足,vector 会重新分配内存并复制元素,导致多次内存分配和复制,降低效率。
#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; }
#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 <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的接口
无法编译通过。因为GradeCalc采用private继承,基类vector<int>的公有接口在GradeCalc中变为私有,外部无法直接访问。
问题3:组合方式:需要在类中定义一个vector<int> grades成员,并提供公有接口或直接暴露成员,数据访问更明确、可控。
继承方式:可以直接使用基类vector<int>的迭代器,数据访问更直接,但封装性较弱,容易暴露内部实现。
问题4:组合。因为组合封装性更好,可以隐藏内部数据存储细节,只暴露必要的接口,而且代码更易维护,组合方式结构清晰,耦合度低,便于测试和扩展。
task3:
#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; } }
#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 <string> #include "Graph.hpp" void test() { Canvas canvas; canvas.add("circle"); canvas.add("triangle"); canvas.add("rectangle"); canvas.paint(); } int main() { test(); }
运行结果截图:

问题1:
(1)std::vector<Graph*> graphs;功能是表示不同的图形,并提供统一的绘制接口 draw()。
(2)class Circle : public Graph;
class Triangle : public Graph;
class Rectangle : public Graph
问题2:
(1)只会执行 Graph 基类的 draw 方法(输出空),不会输出 “draw a circle...”
(2)存储的是 Graph 对象,而不是指针,无法正确存储派生类对象。添加派生类对象时会丢失派生类的特有信息,draw 调用只会调用基类版本。
(3)只会调用基类的析构函数,派生类部分的资源不会被正确释放,导致内存泄漏。
问题3:
Graph.hpp:
在 enum class GraphType 中添加 star。
添加 class Star : public Graph { public: void draw(); };。
Graph.cpp:
实现 Star::draw()
在 str_to_GraphType 函数中添加 "star" 字符串判断。
在 make_graph 的 switch 中添加 case GraphType::star: return new Star;。
问题4:
Canvas 的析构函数中释放。#include "toy.hpp" #include <iostream> using namespace std; int main() { ToyFactory factory; factory.addToy(new BearToy("泰迪宝宝", 129.9)); factory.addToy(new CatToy("喵喵小可爱", 159.9)); factory.addToy(new DogToy("汪汪小英雄", 139.9)); cout << "=== 玩具信息 ===" << endl; factory.displayAllToys(); cout << "\n=== 特异功能 ===" << endl; factory.testAllSpecialFunctions(); return 0; }
#include "toy.hpp" #include <iostream> #include <iomanip> using namespace std; Toy::Toy(const string& name, const string& type, float price) : name_(name), type_(type), price_(price) {} void Toy::displayInfo() const { cout << name_ << " | " << type_ << " | ¥" << fixed << setprecision(1) << price_; } string Toy::getName() const { return name_; } string Toy::getType() const { return type_; } float Toy::getPrice() const { return price_; } BearToy::BearToy(const string& name, float price) : Toy(name, "熊玩具", price) {} void BearToy::performSpecialFunction() const { cout << "唱歌: 小星星"; } CatToy::CatToy(const string& name, float price) : Toy(name, "猫玩具", price) {} void CatToy::performSpecialFunction() const { cout << "跳舞: 华尔兹"; } DogToy::DogToy(const string& name, float price) : Toy(name, "狗玩具", price) {} void DogToy::performSpecialFunction() const { cout << "讲故事: 勇敢的小狗"; } ToyFactory::ToyFactory() {} ToyFactory::~ToyFactory() { for (auto toy : toys_) { delete toy; } } void ToyFactory::addToy(Toy* toy) { if (toy) { toys_.push_back(toy); } } void ToyFactory::displayAllToys() const { for (size_t i = 0; i < toys_.size(); ++i) { cout << "玩具" << (i+1) << ": "; toys_[i]->displayInfo(); cout << endl; } } void ToyFactory::testAllSpecialFunctions() const { for (size_t i = 0; i < toys_.size(); ++i) { cout << "玩具" << (i+1) << " "; toys_[i]->performSpecialFunction(); cout << endl; } }
#ifndef TOY_HPP #define TOY_HPP #include <string> #include <memory> #include <vector> class Toy { public: Toy(const std::string& name, const std::string& type, float price); virtual ~Toy() = default; virtual void displayInfo() const; virtual void performSpecialFunction() const = 0; std::string getName() const; std::string getType() const; float getPrice() const; private: std::string name_; std::string type_; float price_; }; class BearToy : public Toy { public: BearToy(const std::string& name, float price); void performSpecialFunction() const override; }; class CatToy : public Toy { public: CatToy(const std::string& name, float price); void performSpecialFunction() const override; }; class DogToy : public Toy { public: DogToy(const std::string& name, float price); void performSpecialFunction() const override; }; class ToyFactory { public: ToyFactory(); ~ToyFactory(); void addToy(Toy* toy); void displayAllToys() const; void testAllSpecialFunctions() const; private: std::vector<Toy*> toys_; }; #endif
运行结果截图:


浙公网安备 33010602011771号