实验4 组合与继承

实验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;      // 脏标记,记录是否成绩信息有变更
};
GradeCalc.hpp
#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.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();
}
task1.cpp

c5b7bbcd-6ac3-43ec-aa78-c3222d65980c

 问题一:

std::vector<int> grades;存储该课程的所有成绩数据;

std::array<int, 5> counts;统计各分数段的人数;

std::array<double, 5> rates;统计各分数段人数的占比。

问题二:

不合法。

原因:push_back 是 std::vector<int> 的成员函数,而 grades 是 GradeCalc 的私有成员,外部无法直接访问 grades,因此不能通过 GradeCalc 对象直接调用 push_back。

问题三:

1次。用于标记成绩数据是否发生变更。只有当 is_dirty 为 true时,才会重新调用 compute 统计数据;否则直接使用已有统计结果,避免重复计算。

需要。新增 update_grade 会修改成绩数据,需在 update_grade 函数中设置 is_dirty = true,确保后续调用 info 时能触发 compute 重新统计。

问题四:

可在 info 函数中直接计算中位数。

std::vector<int> temp = grades;
std::sort(temp.begin(), temp.end());
double median = 0.0;
if (!temp.empty()) {
size_t n = temp.size();
if (n % 2 == 1) {
median = temp[n / 2];
} else {
median = (temp[n/2 - 1] + temp[n/2]) / 2.0;
}
}
std::cout << "中位数:" << std::fixed << std::setprecision(2) << median << std::endl;
zhongwei

问题五:

不能。若去掉,当多次调用 computer,counts 和 rates 会保留上一次的统计结果,导致新的统计数据与历史数据叠加,最终统计结果错误。

问题六:

无影响。reserve (n) 仅预分配内存,不影响 push_back 的功能,去掉后程序仍能正常录入成绩。

有影响。

若去掉 reserve (n),当录入的成绩数量超过 vector 当前容量时,会触发多次内存重新分配与数据拷贝,导致性能下降。
 
 
 
实验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;      // 脏标记,记录是否成绩信息有变更
};
GradeCalc.hpp
#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;
}
GradeCalc.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();
}
task2.cpp

3434b524-2841-4bea-8e1f-95c80f013a34

问题一:

class GradeCalc: private std::vector<int> {
1
问题二:

不会。

不合法,私有继承下,基类的成员在子类外部不可访问,无法通过 GradeCalc 对象直接调用基类的 push_back 接口。

问题三:

通过组合的成员变量( grades)访问数据,接口由类主动暴露,需类提供访问方法。

通过自身(*this)访问数据,接口继承自基类,但私有继承下外部不可直接使用。

问题四:

组合方案更适合。成绩计算器的核心是 “管理成绩数据” 而非 “成为一个容器”,组合方式更符合 “has-a” 的逻辑,能更灵活地控制数据接口的暴露,同时降低类之间的耦合性,代码的可维护性和扩展性更好。

 

 

 

实验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);  // 创建图形,返回堆对象指针
Graph.hpp
#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.cpp
#include <string>
#include "Graph.hpp"

void test() {
    Canvas canvas;

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

int main() {
    test();
}
demo3.cpp

823bb22c-c8f5-4c51-997c-4d90c0a60037

 问题一:

std::vector<Graph*> graphs;

存储多个图形对象的指针,用于统一管理不同图形实例。

class Circle : public Graph {
class Triangle : public Graph {
class Rectangle : public Graph {

问题二:

 若 Graph 的 draw 未声明为虚函数:Canvas::paint () 中 g->draw () 会调用基类 Graph 的空实现,而非各子类的 draw,无法实现多态。

若 vector<Graph*> 改为 vector<Graph>:会发生 “对象切片”,子类对象存入容器时会被截断为基类对象,丢失子类特性,无法调用子类 draw。

 若~Graph () 未声明为虚函数:删除基类指针指向的子类对象时,仅会调用基类析构函数,子类资源无法释放,导致内存泄漏。

问题三:

Graph.hpp:

在 GraphType 枚举中添加 star;声明 class Star : public Graph {public: void draw (); };。

Graph.cpp:

在 str_to_GraphType 函数中添加 if (t == "star") return GraphType::star;;在 make_graph 的 switch 中添加 case GraphType::star: return new Star;。

问题四:

make_graph 返回的对象在 Canvas 的析构函数中被释放,通过 delete g 遍历 graphs 释放每个指针。

利:实现简单,直接控制对象生命周期;

弊:需手动管理内存,易出现内存泄漏(如忘记 delete)、悬空指针等问题,代码安全性低。

 

 

实验4:

#pragma once
#include <string>
#include <vector>

// 毛绒玩具基类
class Toy {
protected:
    std::string name;    // 玩具名称
    std::string type;    // 玩具类型(如“毛绒熊”)
    int price;           // 价格
public:
    Toy(const std::string& n, const std::string& t, int p) : name(n), type(t), price(p) {}
    virtual ~Toy() = default;

    // 特异功能(虚函数,子类重写)
    virtual void specialFunction() const = 0;

    // 获取玩具信息
    std::string getName() const { return name; }
    std::string getType() const { return type; }
    int getPrice() const { return price; }
};

// 发声玩具(继承Toy)
class SoundToy : public Toy {
private:
    std::string sound;   // 发声内容
public:
    SoundToy(const std::string& n, const std::string& t, int p, const std::string& s) 
        : Toy(n, t, p), sound(s) {}

    void specialFunction() const override;
};

// 发光玩具(继承Toy)
class LightToy : public Toy {
private:
    std::string lightColor; // 发光颜色
public:
    LightToy(const std::string& n, const std::string& t, int p, const std::string& c) 
        : Toy(n, t, p), lightColor(c) {}

    void specialFunction() const override;
};

// 声光玩具(继承Toy)
class SoundLightToy : public Toy {
private:
    std::string sound;
    std::string lightColor;
public:
    SoundLightToy(const std::string& n, const std::string& t, int p, const std::string& s, const std::string& c) 
        : Toy(n, t, p), sound(s), lightColor(c) {}

    void specialFunction() const override;
};

// 玩具工厂类(组合一组Toy)
class ToyFactory {
private:
    std::string factoryName;
    std::vector<Toy*> toys; // 组合:管理多个玩具
public:
    ToyFactory(const std::string& name) : factoryName(name) {}
    ~ToyFactory();

    // 添加玩具
    void addToy(Toy* toy);
    // 展示所有玩具信息并调用特异功能
    void showAllToys() const;
};
Toy.hpp
#include "Toy.hpp"
#include <iostream>

// 发声玩具的特异功能
void SoundToy::specialFunction() const {
    std::cout << "" << name << "】发出声音:" << sound << std::endl;
}

// 发光玩具的特异功能
void LightToy::specialFunction() const {
    std::cout << "" << name << "】发出" << lightColor << "的光" << std::endl;
}

// 声光玩具的特异功能
void SoundLightToy::specialFunction() const {
    std::cout << "" << name << "】发出" << lightColor << "的光,并播放:" << sound << std::endl;
}

// 玩具工厂析构:释放玩具资源
ToyFactory::~ToyFactory() {
    for (Toy* toy : toys) {
        delete toy;
    }
}

// 添加玩具到工厂
void ToyFactory::addToy(Toy* toy) {
    toys.push_back(toy);
}

// 展示所有玩具信息
void ToyFactory::showAllToys() const {
    std::cout << "===== " << factoryName << " 玩具列表 =====" << std::endl;
    for (const Toy* toy : toys) {
        std::cout << "名称:" << toy->getName() 
                  << " | 类型:" << toy->getType() 
                  << " | 价格:" << toy->getPrice() << "" << std::endl;
        toy->specialFunction(); // 统一调用特异功能
        std::cout << "------------------------" << std::endl;
    }
}
Toy.cpp
#include "Toy.hpp"
#include <iostream>

void test() {
    // 创建玩具工厂
    ToyFactory factory("快乐玩具厂");

    // 添加不同类型的玩具
    factory.addToy(new SoundToy("音乐小熊", "毛绒熊", 99, "“你好呀~”"));
    factory.addToy(new LightToy("发光小兔", "毛绒兔", 129, "粉色"));
    factory.addToy(new SoundLightToy("声光恐龙", "毛绒恐龙", 199, "“ roar~”", "红色"));

    // 展示所有玩具信息
    factory.showAllToys();
}

int main() {
    test();
    return 0;
}
task4.cpp

继承关系:Toy→ SoundToy、LightToy、SoundLightToy;

组合关系:ToyFactory包含 std::vector<Toy*>。

 

 

posted @ 2025-12-02 19:16  晚风吹动荷塘月  阅读(3)  评论(0)    收藏  举报