任务一:

源代码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(); 
}
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;  // 更新脏标记
}
GradeCalc.hpp
#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;      // 脏标记,记录是否成绩信息有变更
};

问题1:std::vector<int> grades:动态存成绩;std::array<int,5> counts:存分数段人数;std::array<double,5> rates:存分数段占比。

问题2:不合法,因gradesGradeCalc私有成员,外部无法直接调用其push_back

问题3:(1) compute调用 1 次;is_dirty标记成绩是否变更,避免重复计算。(2) 需要调整,因update_grade改成绩后需设is_dirty=true以触发compute

问题4:在info中临时拷贝成绩排序后计算中位数,伪代码:拷贝grades排序,按奇偶取中间值输出。

问题5:不能去掉;若去掉,多次修改成绩后统计会叠加旧数据,导致结果错误。

问题6:(1) 对功能无影响。(2) 有影响,push_back会多次扩容拷贝数据,降低录入效率。

运行结果截图:

屏幕截图 2025-12-02 195303

 

任务二:

源代码task2.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();
}
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;
}

 问题1:代码行:class GradeCalc: private std::vector<int> {

问题2:不能编译通过;因GradeCalc是私有继承vector<int>,基类接口不会自动成为GradeCalc的接口,外部无法直接调用push_back

问题3:组合方式:通过私有成员对象的接口访问(如grades.push_back()),封装性强,仅暴露自定义接口;继承方式:通过自身(*this)的接口访问(如this->push_back()),私有继承下基类接口被隐藏,仅能在类内部使用。

问题4:组合方案更合适;理由:成绩计算器是 “使用”vector存储数据,而非 “是”vector,组合更符合 “has-a” 的逻辑,且能更好地控制接口暴露,避免基类接口滥用。

运行结果截图:

屏幕截图 2025-12-02 195642

 

任务三

源代码task3.cpp

#include <string>
#include "Graph.hpp"

void test() {
    Canvas canvas;

    canvas.add("circle");
    canvas.add("triangle");
    canvas.add("rectangle");
    canvas.paint();
}

int main() {
    test();
}
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;
    }
}

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);  // 创建图形,返回堆对象指针

 

运行结果截图

屏幕截图 2025-12-02 193150

问题1:(1) 代码行:std::vector<Graph*> graphs;;功能:存储多个图形对象的指针,管理画布中的图形集合。(2) 代码行:class Circle : public Graph {class Triangle : public Graph {class Rectangle : public Graph {

问题2:(1) 会调用Graph的空draw函数,而非子类的draw,无法实现多态(即不会输出具体图形的绘制信息)。(2) 会出现 “对象切片” 问题:子类对象存入vector<Graph>时会被截断为基类对象,丢失子类特性,无法调用子类draw。(3) 会导致子类对象的析构函数无法被调用,引发内存泄漏。

问题3:Graph.hpp:新增Star类(继承Graph)并声明draw函数;Graph.cpp:实现Star::draw函数;Graph.cpp的str_to_GraphType:添加"star"到枚举的映射;Graph.cpp的make_graph:添加Star的创建分支。

问题4:(1) 在Canvas的析构函数中,通过delete g释放。(2) 利:灵活控制对象生命周期;弊:易出现内存泄漏、野指针等问题,需手动管理内存。

任务四

源代码task4.cpp

#include "ToyFactory.h"
#include <iostream>
using namespace std;
int main() {
    ToyFactory factory;
    factory.addToy(new SingingToy("小熊玩偶", "毛绒公仔", "《小星星》"));
    factory.addToy(new LightToy("兔子夜灯", "毛绒灯具", "暖黄色"));
    factory.addToy(new SingingToy("恐龙娃娃", "毛绒摆件", "《快乐崇拜》"));
    factory.showAllToys();

    return 0;
}

Toy.h

#ifndef TOY_H
#define TOY_H
#include <string>
#include<iostream>
using namespace std;
class Toy {
protected:
    string name;   
    string type;   
public:
    Toy(string n, string t) : name(n), type(t) {}
    virtual ~Toy() = default; 
    virtual void specialFunction() const = 0;
    string getName() const { return name; }
    string getType() const { return type; }
};
class SingingToy : public Toy {
private:
    string song; 
public:
    SingingToy(string n, string t, string s) : Toy(n, t), song(s) {}
    void specialFunction() const override {
        cout << "" << name << "】播放歌曲:" << song << endl;
    }
};
class LightToy : public Toy {
private:
    string color; 
public:
    LightToy(string n, string t, string c) : Toy(n, t), color(c) {}
    void specialFunction() const override {
        cout << "" << name << "】发出" << color << "的光" << endl;
    }
};

#endif

ToyFactory.h

#ifndef TOYFACTORY_H
#define TOYFACTORY_H
#include "Toy.h"
#include <vector>
class ToyFactory {
private:
    vector<Toy*> toys; 
public:
    ~ToyFactory() {
        for (auto toy : toys) delete toy;
    }
    void addToy(Toy* toy) {
        toys.push_back(toy);
    }
    void showAllToys() const {
        cout << "\n===== 玩具工厂产品列表 =====" << endl;
        for (const auto& toy : toys) {
            cout << "名称:" << toy->getName() 
                 << " | 类型:" << toy->getType() 
                 << " | 特异功能:";
            toy->specialFunction(); 
        }
    }
};

#endif

运行结果截图:

屏幕截图 2025-12-02 194858

 

posted on 2025-12-02 19:58  mm77777  阅读(1)  评论(0)    收藏  举报