实验4
GradeCalc.h
#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; // 脏标记,记录是否成绩信息有变更 };
GradeCalc.cpp
#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; // 更新脏标记 }
task1.cpp
#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(); }
问题一: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; 保存各分数段人数占比
问题二:不合法,input写成inupt了且push_back是vector的方法而不是GradeCalc的
问题三:一次,用来标记成绩信息是否有变来标记是否需要更新counts和rates
不需要,updata会改变is_dirty标记,触发compute函数
问题四:在info函数里面计算,先定义临时数组temp并复制数据,然后从小到大排序,并按照元素个数算出中位数
问题五:不能,每次改名或者使用compute函数都会导致counts和rates继承之前的数据导致数据错误
问题六:对功能没影响,对效率有影响,vector的频繁push_back会浪费大量时间,提前申请容量可以提高效率
GradeCalc.hpp
#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; // 脏标记,记录是否成绩信息有变更 };
GradeCalc.cpp
#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; }
test2.cpp
#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(); }
问题一:class GradeCalc: private std::vector<int>
问题二:不会
不能通过编译,因为已private的权限继承的vector外部无法使用其接口
问题三:组合是通过对象的成员变量访问
继承是通过vector的基类接口访问数据
问题四:组合更适合因为在语义上是GradeCalc其中拥有vector成员,且vector本身已private继承接口隐藏,不如组合清晰
Graph.hpp
#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); // 创建图形,返回堆对象指针
Graph.cpp
#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; } }
demo3.cpp
#include <string> #include "Graph.hpp" void test() { Canvas canvas; canvas.add("circle"); canvas.add("triangle"); canvas.add("rectangle"); canvas.paint(); } int main() { test(); }
问题一:std::vector<Graph*> graphs; 声明Graph类指针数组
class Circle : public Graph,class Triangle : public Graph,class Rectangle : public Graph
问题二:1:未声明为虚函数会导致始终调用基类的draw函数
2:push_back的数据是Graph*型,类型不匹配报错
3:只有基类的析构函数会被调用,导致内存泄漏
问题三:GraphType枚举列表内要添加星型
str_to_GraphType和make_graph中添加星型的对应分类
添加星型的类声明
问题四:1:会在~Canvas中被释放
2:可以自由分配和释放内存但是安全性差容易内存泄漏
toy.hpp
#pragma once #include <string> #include <vector> enum class ToyType {freddy,bonnie,chica,mangle}; class toy { public: virtual void function() {} virtual void set() {} virtual void _printf() {} virtual ~toy() = default; protected: std::string name; std::string type; std::string color; }; class name1 : public toy { private: void function(); void set(); void _printf(); }; class name2 : public toy { private: void function(); void set(); void _printf(); }; class name3 : public toy { private: void function(); void set(); void _printf(); }; class name4 : public toy { private: void function(); void set(); void _printf(); }; class ToyFactory { public: void add(const std::string& type); void paint() const; ~ToyFactory(); private: std::vector<toy*> toys; }; // 4. 工具函数 ToyType str_to_ToyType(const std::string& s); // 字符串转枚举类型 toy* make_toy(const std::string& type); // 创建图形,返回堆对象指针
toy.cpp
#include <algorithm> #include <cctype> #include <iostream> #include <string> #include "toy.hpp" void name1::set() { name = "freddy"; type = "bear"; color = "brown"; } void name2::set() { name = "bonnie"; type = "rabbit"; color = "blue"; } void name4::set() { name = "mangle"; type = "fox"; color = "orange"; } void name3::set() { name = "chica"; type = "chicken"; color = "yellow"; } void name1::_printf() { std::cout << name << "\n" << type << "\n" << color << "\n"; } void name2::_printf() { std::cout << name << "\n" << type << "\n" << color << "\n"; } void name3::_printf() { std::cout << name << "\n" << type << "\n" << color << "\n"; } void name4::_printf() { std::cout << name << "\n" << type << "\n" << color << "\n"; } void name1::function() { std::cout << "Toy Freddy approaches from the main hallway. He blocks the flashlight, and you must use the Freddy mask to stop him.\n\n"; } void name2::function() { std::cout << "Toy Bonnie moves quickly and enters through the left vent. Putting on the Freddy mask immediately is the only way to avoid him.\n\n"; } void name3::function() { std::cout << "Toy Chica enters through the right vent. She becomes active early, and the player must use the Freddy mask to fool her.\n\n"; } void name4::function() { std::cout << "Mangle makes loud static noises and usually comes through the right vent. Once in the office, the mask won’t reliably stop it.\n\n"; } ToyFactory::~ToyFactory() { for (toy* g : toys) delete g; } void ToyFactory::paint() const { for (toy* g : toys) { g->_printf(); g->function(); } } void ToyFactory::add(const std::string& type) { toy* g = make_toy(type); if (g) toys.push_back(g); g->set(); } // 工具函数实现 // 字符串 → 枚举转换 ToyType str_to_ToyType(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 == "freddy") return ToyType::freddy; if (t == "bonnie") return ToyType::bonnie; if (t == "chica") return ToyType::chica; if (t == "mangle") return ToyType::mangle; return ToyType::freddy; // 缺省返回 } // 创建图形,返回堆对象指针 toy* make_toy(const std::string& type) { switch (str_to_ToyType(type)) { case ToyType::freddy: return new name1; case ToyType::bonnie: return new name2; case ToyType::chica: return new name3; case ToyType::mangle: return new name4; default: return nullptr; } }
demo4.cpp
#include <string> #include "toy.hpp" void test() { ToyFactory canvas; canvas.add("freddy"); canvas.add("bonnie"); canvas.add("chica"); canvas.add("mangle"); canvas.paint(); } int main() { test(); }

toyfactory含一个toy基类数组,name继承了toy基类
只能输出已有信息不能输入

浙公网安备 33010602011771号