实验3

#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();
}

 

 

image

1. std::string course_name;:课程名。

std::vector<int> grades;:课程成绩

std::array<int, 5> counts;:保存各分数段人数

std::array<double, 5> rates;:保存各分数段人数占比 

2.不合法,radesGradeCalc的私有成员,外部无法直接访问c.grades

3.(1)1次,记录是否成绩信息有变更

(2)不需要。

4.info函数,

if (size % 2 == 1) {
        median = temp[size / 2];
    } else {
        median = (temp[size/2 - 1] + temp[size/2]) / 2.0;
    }
}
std::cout << "中位数:\t" << std::fixed << std::setprecision(2) << median << std::endl;

 5.不能,当成绩数据被修改(如多次调用input)时,出现统计错误。

6.无影响,降低程序效率。

 

 

#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();
}

 

 

 

image

 1.class GradeCalc : private std::vector<int

2.不会,私有继承下基类接口不会暴露给外部

3.for(auto grade: grades);封装性强

for(int grade: *this)封装性弱于组合

4.组合,组合更符合语义;且组合的封装性、可维护性(如更换存储容器)更强。

 

#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();
}#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;
    }
}

 

 

image

 1.(1)std::vector<Graph*> graphs;存储多个 Graph 类对象的指针,用于管理画布图形

(2)class Circle : public Graph

class Triangle : public Graph

class Rectangle : public Graph 

2.(1) 若Graph::draw未声明为虚函数,无法实现多态,所有图形都会执行空的基类 draw 逻辑。

(2)丢失子类特有的数据和行为,无法实现多态。

(3)会仅调用基类的析构函数,子类的资源无法被释放

3.Graph.hpp:class Star : public Graph { public: void draw(); };

enum class GraphType { circle, triangle, rectangle, star };

4.(1)Canvas 的析构函数

(2)使用简单;代码安全性低

 

// Toy.hpp
#pragma once

#include <string>
#include <vector>

// 抽象基类:所有毛绒玩具的共同接口
class Toy {
protected:
    std::string name;
    std::string type;
    std::string color;
    double price;

public:
    // 构造函数
    Toy(std::string n, std::string t, std::string c, double p)
        : name(n), type(t), color(c), price(p) {
    }

    // 纯虚函数:特异功能,子类必须实现
    virtual void specialFunction() const = 0;

    // 普通成员函数:显示玩具的基础信息
    void showBasicInfo() const;

    // 虚析构函数:确保子类对象能被正确销毁
    virtual ~Toy() = default;
};

// 具体玩具类:会唱歌的小熊
class SingingBear : public Toy {
public:
    SingingBear(std::string n, std::string c, double p);
    void specialFunction() const override;
};

// 具体玩具类:会发光的兔子
class GlowingRabbit : public Toy {
public:
    GlowingRabbit(std::string n, std::string c, double p);
    void specialFunction() const override;
};

// 具体玩具类:会说话的鸭子
class TalkingDuck : public Toy {
public:
    TalkingDuck(std::string n, std::string c, double p);
    void specialFunction() const override;
};

// 玩具工厂类:管理一组玩具
class ToyFactory {
private:
    std::string factoryName;
    std::vector<Toy*> toyCollection; // 组合:包含一组Toy对象的指针

public:
    ToyFactory(std::string fn);
    ~ToyFactory();

    void addToy(Toy* toy);
    void showAllToys() const;
};
// Toy.cpp
#include "Toy.hpp"
#include <iostream>
#include <iomanip>

// --- Toy 类的实现 ---
void Toy::showBasicInfo() const {
    std::cout << "名称:" << name
        << " | 类型:" << type
        << " | 颜色:" << color
        << " | 价格:" << std::fixed << std::setprecision(2) << price << "";
}

// --- SingingBear 类的实现 ---
SingingBear::SingingBear(std::string n, std::string c, double p)
    : Toy(n, "小熊", c, p) {
}

void SingingBear::specialFunction() const {
    std::cout << "【特异功能】" << name << "开始唱歌:\"两只老虎,跑得快~\"" << std::endl;
}

// --- GlowingRabbit 类的实现 ---
GlowingRabbit::GlowingRabbit(std::string n, std::string c, double p)
    : Toy(n, "兔子", c, p) {
}

void GlowingRabbit::specialFunction() const {
    std::cout << "【特异功能】" << name << "的耳朵开始发光,颜色是" << color << "" << std::endl;
}

// --- TalkingDuck 类的实现 ---
TalkingDuck::TalkingDuck(std::string n, std::string c, double p)
    : Toy(n, "鸭子", c, p) {
}

void TalkingDuck::specialFunction() const {
    std::cout << "【特异功能】" << name << "说:\"你好呀,我是你的小鸭子~\"" << std::endl;
}

// --- ToyFactory 类的实现 ---
ToyFactory::ToyFactory(std::string fn) : factoryName(fn) {}

ToyFactory::~ToyFactory() {
    // 析构函数:释放所有通过 new 创建的 Toy 对象
    for (Toy* toy : toyCollection) {
        delete toy;
    }
    toyCollection.clear();
    std::cout << "\n" << factoryName << "已关闭,所有玩具已销毁。" << std::endl;
}

void ToyFactory::addToy(Toy* toy) {
    if (toy != nullptr) {
        toyCollection.push_back(toy);
    }
}

void ToyFactory::showAllToys() const {
    std::cout << "\n===== " << factoryName << " 玩具列表 =====\n";
    if (toyCollection.empty()) {
        std::cout << "工厂里暂时没有玩具。" << std::endl;
        return;
    }
    for (size_t i = 0; i < toyCollection.size(); ++i) {
        std::cout << "\n" << i + 1 << ". ";
        toyCollection[i]->showBasicInfo(); // 调用基类方法
        toyCollection[i]->specialFunction(); // 调用子类重写的方法(多态)
    }
    std::cout << "=============================\n";
}
// main.cpp
#include "Toy.hpp"

int main() {
    // 1. 创建一个玩具工厂
    ToyFactory happyFactory("快乐毛绒玩具厂");

    // 2. 向工厂添加不同的玩具
    // 注意:这里使用 new 创建对象,所有权交给 ToyFactory
    happyFactory.addToy(new SingingBear("音乐小熊", "棕色", 59.9));
    happyFactory.addToy(new GlowingRabbit("发光小兔", "粉色", 49.9));
    happyFactory.addToy(new TalkingDuck("会说话的鸭鸭", "黄色", 39.9));

    // 3. 显示工厂里所有玩具的信息
    happyFactory.showAllToys();

    // 4. 程序结束时,happyFactory 对象会被销毁
    // 它的析构函数会自动 delete 所有添加的 Toy 对象,防止内存泄漏

    return 0;
}

 

 

image

 

posted @ 2025-11-26 00:09  HdYi  阅读(2)  评论(0)    收藏  举报